组件的定义
定义组件:
1.函数式定义:
<div id="test"></div> <script type="text/babel"> // 创建函数式组件 function Demo (){ return <h2>定义的简单组件</h2> } ReactDom.render(<Demo />, document.getElementById('test')) </script>
2. 类定义
class component1 extends React.Component {
render(){
// render放在component1的原型对象上,供实例使用
return <div>454545</div>
}
}
ReactDom.render(<Componet1 />, document.getElemntById('test'))
// React解析组件标签,找到component1组件
// 发现组件是用类定义的,然后new 出该类的实例,并调用其身上的render函数
// 将render返回的虚拟DOM转化为真实DOM,渲染到页面上
class Weather extends React.Component {
constructor(props){
supper(props)
// 初始化状态
this.state = { isHot: false }
// 改变this指向,把原型上的方法放到本身上.
// 解决changeWeather中this的问题
this.changeWeather = this.changeWeather.bind(this)
}
render(){
// 读取状态
const {isHot} = this.state
return <h1 onClick={ this.changeWeather }>今天天气很{ this.isHot ? '热' : '冷' }</h1>
}
changeWeather(){
// 放在Wearther的原型对象上, 供实例使用
// 由于changeWeather是作为click的回调,是直接调用
// 类中的方法默认开启了严格模式, 所以方法中的this为undefined
console.log(this)
// 注意!!state中的数据不可直接更改,要用setState方法,是一种合并动作,不是更换
// 直接更改 this.state = true
this.setState({ isHot: true })
}
}
ReactDom.render(<Componet1 />, document.getElemntById('test'))
简洁形式 ===== 》 》》》
class Weather extends React.Component {
// 初始化状态
state = { isHot: false }
render(){
const {isHot} = this.state
return <h1 onClick={ this.changeWeather }>今天天气很{ this.isHot ? '热' : '冷' }</h1>
}
// 自定义方法 ----要用赋值语句+箭头函数形式
changeWeather = () => {
console.log(this)
// 注意!!state中的数据不可直接更改,要用setState方法,是一种合并动作,不是更换
// 直接更改 this.state = true
this.setState({ isHot: true })
}
}
ReactDom.render(<Componet1 />, document.getElemntById('test'))

浙公网安备 33010602011771号