父组件
import React, { Component } from 'react'; import Child from './child'; export default class Home extends Component { constructor(props) { super(props); this.ref = React.createRef(); this.state = { name: '', visible: true, }; } getObj = () => { const obj2 = { name: '李四', age: 33, education: '博士', sex: '男', }; return obj2; }; goIn = val => { console.log(val); this.setState({ visible: val, }); }; componentDidMount() { //必须在这里面获取,这时候DOM才挂载完成 const { name } = this.ref.current.state; this.setState({ name }); } render() { const obj = { name: '张三', age: 30, education: '博士', sex: '男', }; return ( <div style={{ height: '100%', backgroundColor: '#fff' }}> <h2 style={{ fontSize: '30px' }}>父组件</h2> <div>父传子,子用父亲里面的数据</div> <Child obj={obj} parent={this} setFun={this.getObj} ref={this.ref} goInChind={this.goIn} /> <div>姓名:{this.state.name}</div> <div style={{ visibility: this.state.visible ? 'visible' : 'hidden' }}> 根据子组件的参数显示隐藏 </div> </div> ); } }
子组件
import React, { Component } from 'react'; import PropTypes from 'prop-types'; export default class Child extends Component { static propTypes = { obj: PropTypes.object.isRequired, //isRequired 是否必须,不添加就是可以不传 setFun: PropTypes.func.isRequired, parent: PropTypes.object.isRequired, }; constructor(props) { super(props); const obj = this.props.obj; this.state = { obj: obj, obj2: {}, name: '王二', visible: this.props.parent.state.visible, }; this.inputRef = React.createRef(); } eventClick = () => { const obj2 = this.props.setFun(); this.setState({ obj2 }); }; methodToParent = () => { console.log(1111); }; handle = () => { this.props.goInChind(!this.state.visible); this.setState({ visible: !this.state.visible, }); }; render() { const { obj, obj2 } = this.state; const { name, age, education, sex } = obj; return ( <div style={{ backgroundColor: '#fff' }}> <div style={{ border: '1px solid #ccc', padding: '5px', '200px', backgroundColor: '#f1f1f1', }} > <p>姓名:{name}</p> <p>年纪:{age}</p> <p>学历:{education}</p> <p>性别:{sex}</p> </div> <div style={{ marginTop: '20px' }}> <h2> 父传子,子调用父亲函数产生的数据 <span onClick={this.eventClick} style={{ backgroundColor: '#008255', padding: '0px 10px', color: '#fff', marginLeft: '10px', cursor: 'pointer', }} > 点击 </span> </h2> <p>姓名:{obj2.name}</p> <p>年纪:{obj2.age}</p> <p>学历:{obj2.education}</p> <p>性别:{obj2.sex}</p> </div> <div style={{ marginTop: '20px' }}> <h2>子传父,父亲调用子里面的数据</h2> <div onClick={this.handle} style={{ backgroundColor: '#008255', padding: '0px 10px', color: '#fff', marginLeft: '10px', cursor: 'pointer', '60px', }} > 点击 </div> </div> </div> ); } }
总结
子获取父亲的数据,父亲定义,子组件this.props
父获取子组件的信息,子组件挂载句柄ref,父组件通过current获取
还有一个方法是传函数
父组件
子组件