React 组件通信
父传子
函数式组件
function Footer(props){const [count,setCount] = useState(0)const {name,age} = propsconst onClick = ()=>{setCount(count+1)}return (<div><button onClick={()=>{onClick()}}>点此+1</button><div>{count}</div><div>name是:{name}年龄是:{age}</div></div>)
}
类组件
class Header extends React.Component{constructor(props){super()this.props = props}render(){const {name,age} = this.propsreturn (<div><div>name是:{name}年龄是:{age}</div> </div>)}
}
也可以直接在constructor中super(props)
constructor(props){super(props)}
通信时的属性验证
进行一个typescript的使用
父传子 通过回调函数
类组件中
class CounterButton extends React.Component{constructor(props){super(props)}render(){const {handlecallback} = this.propsreturn (<button onClick={handlecallback}>接口anniu组件</button>)}
}
如图,通过props中父组件传递过来的increase函数实现增加
父组件传值
<CounterButton handlecallback={this.increase}/>
函数式组件中
function DeButton(props){const {handlecallback} = propsreturn (<button onClick={handlecallback}>函数式子减小button</button>)
}
父组件传值
<DeButton handlecallback={this.decrease}></DeButton>
父传更远的子代的传递 Context