第一种:
通过定义函数实现
1、父组件设置含有this.setState({...})的方法,形参为接收子组件的变量
2、将方法作为参数传递给子组件
如<B sub={this.方法.bind(this)]/>
3、子组件通过this.props.键名接收函数
this.props.键名(子组件的数据)
第二种:
通过父元素传递的函数在标签中通过箭头函数,直接传参
如:<button onClick={()=>{this.props.函数(参数)}}></button>
代码示例:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
//父组件
class A extends React.Component{
constructor(props){
//将props传递给父类构造器
super(props);
this.state={
flag:true,
info:''
}
}
render()
{
return(
<div>父组件
<h1>{this.state.info}</h1>
<B change={this.receive}/>
</div>
)
}
receive=(msg)=>
{
this.setState({
info:msg
})
}
}
//子元素
class B extends React.Component{
constructor()
{
super();
this.state={
msg:'jeff'
}
}
render()
{
return(
<div>
//方式一
<button onClick={this.send.bind(this)}>传给父元素</button>
//方式二
<button onClick={()=>{this.props.change('哈哈哈')}}>传给父元素方式2</button>
</div>
)
}
send()
{
this.props.change(this.state.msg)
}
}
ReactDOM.render(<A/>, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();