在react中,prop是从组件外部传递给组件的数据,一个React组件通过定义自己能够接受的prop就定义了自己对外公共接口,每个组件都是独立存在的模块,组件之外的一切都是外部世界,外部世界就要通过prop来和其他的组件进行对话(数据的传递)。
prop是如何传递数据的呢?很简单给组件标签添加属性的方式。
eg:<Hello name="ladeng" age={15}/>
组件如何接受外部传来的数据:
①函数组件通过参数props接受数据
//传递数据
<Hello name="ladeng" age={15}/>
//接受数据
function Hello(props){
console.log(props)
return(
<div>接收到数据:{props.name}</div>
)
}
②类组件通过this.props接收数据
class Hello extends React.Component{
render(){
return(
<div>接收到的数据:{this.props.age}</div>
)
}
}
<Hello name="ladeng" age={15}/>
他可以给组件传递给任何格式的数据,但是一切非字符串的数据都要加上大括号
props是只读的对象,只能读取属性的值,无法修改对象。
使用类组件时,如果写了构造函数,应该将props传递给super(),否则,无法在构造函数中获取到props!
组件通讯的三种方式
Ⅰ.父组件传递数据给子组件
1.父组件提供要传递的state数据。
2.给子组件标签添加属性,值为state中的数据。
3.子组件中通过props接受父组件中传递的数据。
class Parent extends React.Component{
state ={lastName:'王'}
render(){
传递数据给子组件:<Clild name={this.state.lastName}/>
}
}
//函数式子组件
function Child(props){
return <div>子组件接受到数据:{props.name}</div>
}
//类组件
Ⅱ,子组件向父组件传值
思路;利用回调函数,父组件提供回调,子组件调用,将要传递的数据作为回调函数的参数。跟VUE中思路相同
1.父组件提供一个回调函数(用于接受数据)
2.将该函数作为属性的值,传递给子组件
3.子组件通过props调用回调函数
4.将子组件的数据作为参数传递给回调函数
//父组件
class Father extends React.Component{
GetChildMsg=(msg)=>{
console.log("接受到子组件的数据");
}
render(){
return(
<div>
子组件:<Child getMsg={this.GetClildMsg}/>
)}
}
//子组件
class Child extends React.Component{
state = {
childMsg:'React'
}
handClick=()=>{
this.props.getMsg(this.state.childMsg)
}
return (
<button onClick={this.handClick}>点我,给父组件传递信息</div>
)
}
Ⅲ.兄弟组件之间的通信
将共享状态提升到最近的公共组件中,由公共组件管理这个状态
状态提升
公共组件职责:1提供共享的状态 2.提供操作共享状态的方法
要通讯的子组件只徐亚通过props接受状态或操作状态的方法。
//父组件
class Counter extends React.Component{
//提供共享状态
state={
count:0
}
//提供修改状态的方法
onIncrement=()=>{
this.setState({
count:this.state.count+1
})
}
render(){
return(
<div>
<Child1 count={this.state.count}/>
<Child2 onIncrement={this.onIncrement}/>
</div>
)
}
}
//子组件1
const Child1=(props)=>{
return <h1>计数器:{props.count}</h1>
}
//子组件2
const Child2=(props)=>{
return <button onClick={props.onIncrement}>+1</button>
}
React.render(<Counter/>,document .getElementById('root')
514



被折叠的 条评论
为什么被折叠?



