父传子
class Test extends React.component{
reder() {
let {title} = this.props
return (
<h4>
{title}
<h4/>
)
}
}
// 父组件
ReactDOM.render(<>
<Test title = {'帅子'}/>
</>,document.getElementById('root')
);
父组件通过属性来传值给子组件
1:只能父亲调用子组件的时候传递(只能父传子, 属于单向的)
2:但是可以基于回调函数的机制实现’子改父’
=> 把父组件中的一个方法,当作属性传递给子组件
=> 子组件接收到这个方法
=> 再子组件把这个方法执行, 从而实现对父组件中的一些信息修改
子传父
class Test extends React.component{
reder() {
let {title} = this.props
return (
<h4 onClick={
this.props.changes.bind(this,'0')
}>
{title}
<h4/>
)
}
}
// 父组件
class App extends React.component{
reder() {
let {title} = this.props
changes(name){
console.log(name)
}
return (
<Test title={'帅子'} changes={changes} />
)
}
}
执行上下文
context
// 父组件
// 在组件元素上注册后代需要使用的信息
// 设置类型
static childrentextTypes = {
title: PropsTypes.string
}
getChildContext() {
// => getChildContext会在第一次属性和状态都初始化之后执行, 和组件重新执行渲染的时候执行(保证使用的属性和状态是最新的)
return {
title: this.state.tite
}
}
// 获取上下文中的信息使用
// 设置属性
static contextTypes
={
title: PropsTypes.string
}
let {title} = this.content
祖先和后台, 或者具备共同祖先的兄弟或者不相关的组件