compontent - communication
- 单向数据源
1.组件数据源:state / props
- props 是 组件的对外接口
上层组件props :数据(计算出来的结果/上一层组件的props/组件自身维护的状态state)和 方法(传递给下一层组件) - state 是 组件的对内接口
对内使用,私有的;每个组件都在维护自己的私有状态
2.视图层变化依据:props 和 state ,它们变化,react机制会重新计算,进而重新渲染
- 单向数据流
数据流动:父 - > 子(子组件不能直接改变父组件的数据:子组件通过父组件传递的行为(也是绑定的属性)来改变父组件的状态)
![在这里插入图片描述](https://img-blog.csdnimg.cn/154effb847c04ce1b36c1136f241f937.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBAYmFsYW5jZX5-,size_20,color_FFFFFF,t_70,g_se,x_16)
<script type="text/babel">
function C3(props) {
console.log('C3', props);
return (
<div>
<h2>C3 组件</h2>
<button onClick={props.click}>button</button>
</div>
)
}
function C2(props) {
console.log('C2', props);
return (
<div>
<h2>C2 组件</h2>
<C3 {...props} />
</div>
)
}
function C1(props) {
console.log('C1', props);
return (
<div>
<h2>C1 组件</h2>
<C2 {...props} />
</div>
)
}
class App extends React.Component {
state = { name: 'jack', age: 18, single: false }
handleClick = () => {
this.setState({
single: true
})
}
render() {
return (
<div>
<h1>App组件</h1>
<h3>single:{this.state.single ? '否' : '是'}</h3>
<C1 {...this.state} click={this.handleClick} />
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById("app"));
</script>
-
瀑布流 由多个组件组成的组件树(props 和 state)
组件通信
- 父传子
- 子传父:回调函数、context、redux 公共状态
- 安检
<body>
<div id="app"></div>
<script src="../js/react.development.js"></script>
<script src="../js/react-dom.development.js"></script>
<script src="../js/babel.min.js"></script>
<script src="../js/prop-types.js"></script>
<script type="text/babel">
class Student extends React.Component {
render() {
console.log(this.props);
let { name, age } = this.props
return (
<ul>
<li>name:{name}</li>
<li>age:{age}</li>
</ul>
)
}
}
Student.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired
}
const student = {
name: 'jack',
age: 18
}
ReactDOM.render(<Student {...student} />, document.getElementById("app"));
</script>
</body>
<!-- 引入库 -->
<script src="../js/react.development.js"></script>
<script src="../js/react-dom.development.js"></script>
<script src="../js/babel.min.js"></script>
<script type="text/babel">
class Student extends React.Component {
static defaultProps={
single:'保密'
}
static propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired
}
render() {
console.log(this.props);
let { name, age, single } = this.props
return (
<ul>
<li>name:{name}</li>
<li>age:{age}</li>
<li>single:{single}</li>
</ul>
)
}
}
const student = {
name: 'jack',
age: 18
}
ReactDOM.render(<Student {...student} />, document.getElementById("app"));
</script>
|