React中组件的props和(父子,子父,兄弟)组件之间传递数据
1.组件的props
1.组件是封闭的,要接收外部数据应该通过props
来实现;
2.props
作用:接收传递给组件的数据;
3.传递数据:给组件标签添加属性;
4.接收数据:函数组件通过参数props
接收数据,类组件通过this.props
接收数据;
//函数组件chuan
<App name="zs" age={18} />
function App(props) {
console.log(props)
return (
<div>接收到数据:{props.name}</div>
)
}
//类组件
class App extends React.Component {
render() {
return (
<div>接收到的数据:{this.props.age}</div>
)
}
}
<App name="zs" age={18} />
特点 :
1.可以给组件传递任意类型的数据;
2.props是只读属性,只能读取属性的值,无法修改对象;
3.使用类组件时,如果写了构造函数,应该将props传递给super(),否则无法在构造函数中获取到props;
Class App extends React.Component{
constructor(props) {
//推荐给props传递构造函数
super(props)
}
render() {
return() {
return <div>接收到的数据:{this.props.age} <div/>
}
}
}
2.组件之间的传递数据
2.1父组件传递数据给子组件
1.父组件提供要传递的state数据;
2.给子组件标签添加属性,值为state中的数据;
3.子组件通过props接收组件中传递的数据;
//定义一个父组件
class Parent extends React.Component{
state = {myName:'zs'}
render() {
return (
<div>
传递数据给子组件: <Child name={this.state.myName} />
<div/>
)
}
}
//定义子组件
function Child(props) {
//函数组件通过props获取到父组件传递来的数据
return <div> 子组件接收到数据:{props.name} <div/>
}
2.2子组件传递数据给父组件
1.利用回调函数,父组件提供回调,子组件调用,将要传递的数据作为回调函数的参数;
2.父组件准备一个回调函数(用于接收数据);
3.将该函数作为属性的值,传递给子组件;
//父组件
class Parent extends React.Component {
//父组件提供的函数
getChildData = (data) => {
console.log('接收到子组件的数据',data)
}
render() {
return (
<div>
{/* 把父组件定义的函数通过属性(props)给子组件 */}
子组件: <Child getData = {this.getChildData} />
<div/>
)
}
}
//子组件
class Child extends React.Component{
state = {
childData:'我是子组件中的数据'
}
//事件处理函数
handleClick = ()=>{
//类组件通过this.props获取传递过来的函数,然后调用
//然后把子组件中的数据通过参数传递给父组件
this.props.getData(this.state.childData)
}
return (
<button onClick={this.handleClick}> 点击按钮给父组件传递数据<button/>
)
}
2.3 兄弟组件之间的传递数据
1.将共享状态提升到最近的公共父组件中,由公共父组件管理这个状态;
2.公共父组件的职责:1.提供共享状态,2.提供操作共享状态的方法;
3.要通讯的子组件只需要通过props接收状态或者操作状态;
// 公共父组件
class Counter extends React.Component {
// 提供共享状态
state = {
count:0
}
// 提供修改状态的方法
onIncrement = () => {
this.setState({
count:this.state.count + 1
})
// console.log(this.state.count)
}
render() {
return (
<div>
{/* 作为参数由公共父组件传递过来 */}
<Child1 count = {this.state.count} />
{/* 子组件2调用公共修改状态方法修改count的值,来改变子组件1中的数据 */}
<Child2 onIncrement={this.onIncrement} />
</div>
)
}
}
// 子组件1
const Child1 = props=>{
//函数组件通过props获取到数据
return <h1>计数器:{props.count}</h1>
}
// 子组件2
const Child2 = props=>{
//子组件2中调用公共父组件中的函数修改count数据,使count加1,子组件1中数据修改
return <button onClick={()=>props.onIncrement()}>+1</button>
}