三大核心属性之state
1、state是组件对象最重要的属性,值是对象(可以包含多个key-value的组合)
2、组件被称为“状态机”,通过更新组件的state来对应更多的页面显示(重新渲染组件)
3、react核心理念状态不可变(专业!!)
class MyComponent extends React.Component{
constructor(props){
super(props)
this.state={isHot:false}
}
render(){
const {isHot}=this.state
return <h1 onClick={this.change}>我是{isHot?'洋洋':'咩咩'}</h1>
}
change=()=>{
let isHot=this.state.isHot
this.setState({isHot:!isHot})//父组件的属性
}
}
ReactDOM.render(<MyComponent/>,document.getElementById('test'))
三大核心属性之props
class Person extends React.Component {
// 对标签属性进行类型、必要性限制
static propTypes = {
name: PropTypes.string.isRequired,//限制name必传,且为字符串
sex: PropTypes.string,//限制sex为字符串
age: PropTypes.number,//限制sex为数值
speak: PropTypes.func,//限制speak为函数
}
// 指定默认标签属性值
static defaultProps = {
name: 'uu',
age: 25
}
render() {
const { name, age } = this.props
return (
<ul>
<li>{name}</li>
<li>{age}</li>
</ul>
)
}
}
const pp = { name: 'kk', age: '18' }
ReactDOM.render(<Person {...pp} />, document.getElementById('test'))
三大核心属性之refs
字符串写法
回调写法showInput=(c)=>{this.input1=c}/////////////
class Component extends React.Component {
showIpt=()=> {
const {input1} =this.refs
console.log(input1.value);
}
showIpt1=()=>{
const {input2} =this
console.log(input2.value);
}
render() {
return (
<div>
<input ref='input1' type="text" placeholder='请输入left' />
<button onClick={this.showIpt}>点击左侧文本显示</button>
<input ref={(c)=>this.input2=c} onBlur={this.showIpt1} type="text"
placeholder='请输入right' />
</div>
)
}
}
ReactDOM.render(<Component />, document.getElementById('test'))
关于回调refs的说明
如果ref回调函数是以内联函数的方式定义的,在更新过程中它会被执行两次,第一次传入参数null,然后第二次会传入参数DOM元素。这是因为在每次渲染时会创建一个新的函数实例,所以React清空旧的ref并且设置新的。通过将ref的回调函数定义成class的绑定函数的方式上避免上述问题,但是大多数情况下它是无关紧要的。
class Person extends React.Component {
state = { isHot: true }
isWeatherChange = () => {
const { isHot } = this.state
this.setState({isHot:!isHot})
}
showInput=(c)=>{
this.input1=c
console.log('@',c);
}
render() {
const { isHot } = this.state
return (
<div>
{/*如果这么写,每次结构更新的时候都会执行一次 但是可以忽略*/}
{/*<input ref={(c)=>{this.input1=c;console.log('@',c);}}
type="text" /> */}
<input ref={this.showInput} type="text" />
<button>点击左侧文本显示</button>
<br />
<button onClick={this.isWeatherChange}>点击切换文字</button>
<p>今天天气真{isHot ? '炎热' : '凉爽'}</p>
</div>
)
}
}
ReactDOM.render(<Person />, document.getElementById('test'))
refs的React.createRef写法
class Person extends React.Component {
showInput1=React.createRef()
showInput2=React.createRef()
clickBtn=()=>{
console.log(this.showInput1.current.value);
}
blurIpt=()=>{
console.log(this.showInput2.current.value);
}
render() {
return (
<div>
<input ref={this.showInput1} type="text" />
<button onClick={this.clickBtn}>点击左侧文本显示</button>
<input onBlur={this.blurIpt} ref={this.showInput2} type="text" />
</div>
)
}
}
ReactDOM.render(<Person/>,document.getElementById('test'))