react均是以组件构成,那父子组件传值就很重要了
父组件传值给子组件,不仅可以传值,传事件,还可以传实例
1、父组件传值给子组件
传值
父组件:
import React from ‘react‘; import Children from ‘./Children‘; class Father extends React.Component { constructor(props) { super(props); this.state = { msg:‘父组件的msg‘ }; } render() { return ( <div> <div>我是父组件</div> <Children msg={this.state.msg}/> </div> ); } } export default Father;
子组件:
import React from ‘react‘; class Children extends React.Component { constructor(props) { super(props); this.state = { msg:‘子组件‘ }; } render() { return ( <div> <div>子组件</div> <div>{this.props.msg}</div> </div> ); } } export default Children;
效果如下:
传事件:
父组件:
import React from ‘react‘; import Children from ‘./Children‘; class Father extends React.Component { constructor(props) { super(props); this.state = { msg:‘父组件的msg‘ }; } run=()=>{ alert(‘给子组件获取事件‘) } render() { return ( <div> <div>我是父组件</div> <Children msg={this.run}/> </div> ); } } export default Father;
子组件:
import React from ‘react‘; class Children extends React.Component { constructor(props) { super(props); this.state = { msg:‘子组件‘ }; } render() { return ( <div> <div>子组件</div> <div>{this.state.msg}</div> <button onClick={this.props.msg}>获取父组件的事件</button> </div> ); } } export default Children;
效果如下:
获取父组件的整个实例
父组件:
import React from ‘react‘; import Children from ‘./Children‘; class Father extends React.Component { constructor(props) { super(props); this.state = { msg:‘父组件的msg‘ }; } run=()=>{ alert(‘给子组件获取事件‘) } render() { return ( <div> <div>我是父组件</div> <Children msg={this}/> </div> ); } } export default Father;
子组件:
import React from ‘react‘; class Children extends React.Component { constructor(props) { super(props); this.state = { msg:‘子组件‘ }; } render() { return ( <div> <div>子组件</div> <div>{this.state.msg}</div> <div>获取父组件的值{this.props.msg.state.msg}</div> <button onClick={this.props.msg.run}>获取父组件的事件</button> </div> ); } } export default Children;
效果如下:
2、子组件传值给父组件,通过ref传值
父组件:
import React from ‘react‘; import Children from ‘./Children‘; class Father extends React.Component { constructor(props) { super(props); this.state = { msg:‘父组件的msg‘ }; } getData=()=>{ this.setState({ msg:this.refs.children.state.msg }) } render() { return ( <div> <div>我是父组件</div> <div>{this.state.msg}</div> <Children ref=‘children‘/> <button onClick={this.getData}>获取子组件</button> </div> ); } } export default Father;
子组件:
import React from ‘react‘; class Children extends React.Component { constructor(props) { super(props); this.state = { msg:‘子组件‘ }; } render() { return ( <div> <div>子组件</div> </div> ); } } export default Children;
效果如下:
原文地址:https://www.cnblogs.com/zdping/p/10320964.html
时间: 2024-11-06 15:35:10