这是我参与「第五届青训营 」伴学笔记创作活动的第 9 天
学习笔记
React的学习4
父传子的具体代码:
1.父组件提供要传递的state数据
class Parent extends React.Component {
state = {
iq: 100,
};
render() {
return (
<div>
<h1>父:{this.state.iq}</h1>
</div>
);
}
}
2.给子组件标签添加属性,值为state中的数据
class Parent extends React.Component {
//......与上一条的代码一致
<h1>父:{this.state.iq}</h1>
+ <Child money={this.state.iq} />
//......
}
3.子组件中通过props接收父组件中传递的数据
function Child(props) {
return (
<div>
<h2>子:{props.iq}</h2>
</div>
);
}
父组件声明state,子组件标签属性绑定,通过props使用。
子传父方式
- 父组件提供回调函数,通过 props 传递给子组件
- 子组件调用 props 中的回调函数,函数可传参
- 父组件函数的参数就是子组件传递的数据
具体代码: 父组件
class Parent extends React.Component {
state = {
iq: 100,
};
// 回调函数
buyIq = (buy) => {
this.setState({
iq: this.state.iq + buy,
});
};
render() {
const { iq } = this.state;
return (
<div>
<h1>父:{iq}</h1>
<Child iq={iq} buyIq={this.buyIq} />
</div>
);
}
}
子组件
const Child = (props) => {
const handleClick = () => {
// 子组件调用父组件传递过来的回调函数
props.buyIq(5);
};
return (
<div>
<h2>子:{props.iq}</h2>
<button onClick={handleClick}>buy iq</button>
</div>
);
};
子组件通过父组件传递的回调函数来传入数据,回调函数的参数是子组件传递的数据,父组件数据更新后,传递给子组件的数据自动更新。
兄弟组件之间的通讯
由最近的公共父组件来进行管理共享状态和这个状态的修改。
代码:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
// 导入两个子组件
import abc from './abc';
import bbb from './bbb';
// App 是父组件
class App extends Component {
// 1. 状态提升到父组件
state = {
msg: '',
};
changeMsg = (msg) => {
this.setState({ msg });
};
render() {
return (
<div>
<h1>我是App组件</h1>
{/* 兄弟组件 1 */}
<abc changeMsg={this.changeMsg}></abc>
{/* 兄弟组件 2 */}
<bbb msg={this.state.msg}></bbb>
</div>
);
}
}
// 渲染组件
ReactDOM.render(<App />, document.getElementById('root'));
子组件:
import React, { Component } from 'react';
export default class Jack extends Component {
say = () => {
// 修改数据
this.props.changeMsg('I SEE');
};
render() {
return (
<div>
<h3>abc组件</h3>
<button onClick={this.say}>说</button>
</div>
);
}
}
import React, { Component } from 'react';
export default class Rose extends Component {
render() {
return (
<div>
<h3>bbb组件-{this.props.msg}</h3>
</div>
);
}
}