state:
要使用class中的构造函数:constructor
//构造器调用几次? ———— 1次
constructor(props){
super(props)
}
事件处理使用changeWeather,改变数据需要用this.setState()
//changeWeather调用几次? ———— 点几次调几次
changeWeather(){
//changeWeather放在哪里? ———— Weather的原型对象上,供实例使用
//由于changeWeather是作为onClick的回调,所以不是通过实例调用的,是直接调用
//类中的方法默认开启了局部的严格模式,所以changeWeather中的this为undefined
console.log('changeWeather');
//获取原来的isHot值
const isHot = this.state.isHot
//严重注意:状态必须通过setState进行更新,且更新是一种合并,不是替换。
this.setState({isHot:!isHot})
//严重注意:状态(state)不可直接更改,下面这行就是直接更改!!!
}
简写:
//1.创建组件
class Weather extends React.Component{
constructor(props){
super(props)
}
//初始化状态
state = {isHot:false,wind:'微风'}
render(){
const {isHot,wind} = this.state
return <h1 onClick={this.changeWeather}>今天天气很{isHot ? '炎热' : '凉爽'},{wind}</h1>
}
//自定义方法————要用赋值语句的形式+箭头函数
changeWeather = ()=>{
const isHot = this.state.isHot
this.setState({isHot:!isHot})
}
}
//2.渲染组件到页面
ReactDOM.render(<Weather/>,document.getElementById('test'))
props:
- 扩展属性: 将对象的所有属性通过props传递<Person {...person}/>
//对标签属性进行类型、必要性的限制:static propTypes = {};isRequired为必传
//指定默认标签属性值 : static defaultProps = {}
//创建组件
class Person extends React.Component{
constructor(props){
//构造器是否接收props,是否传递给super,取决于:是否希望在构造器中通过this访问props
// console.log(props);
super(props)
console.log('constructor',this.props);
}
//对标签属性进行类型、必要性的限制
static propTypes = {
name:PropTypes.string.isRequired, //限制name必传,且为字符串
sex:PropTypes.string,//限制sex为字符串
age:PropTypes.number,//限制age为数值
}
//指定默认标签属性值
static defaultProps = {
sex:'男',//sex默认值为男
age:18 //age默认值为18
}
render(){
// console.log(this);
const {name,age,sex} = this.props
//props是只读的
//this.props.name = 'jack' //此行代码会报错,因为props是只读的
return (
<ul>
<li>姓名:{name}</li>
<li>性别:{sex}</li>
<li>年龄:{age+1}</li>
</ul>
)
}
}
//渲染组件到页面
ReactDOM.render(<Person name="jerry"/>,document.getElementById('test1'))
refs:不建议多使用refs
有字符串,回调函数,React.createRef三种创建,
字符串
<input ref="input1" type="text" placeholder="点击按钮提示数据"/>
接收
const {input1} = this.refs
alert(input1.value)
回调函数:通常回调函数使用比较多
<input ref={c => this.input1 = c } type="text" placeholder="点击按钮提示数据"/>
接收
const {input1} = this
alert(input1.value)
执行函数:
<input ref={this.myRef} type="text" placeholder="点击按钮提示数据"/>
执行
myRef = React.createRef()
alert(this.myRef.current.value);