在这里,您可以轻松地看到从父级
上的子项运行函数的方法http://andrewhfarmer.com/component-communication/#3-callback-functions
虽然如何从孩子那里传递一个带有该功能的参数?
答案 0 :(得分:2)
如果你需要父组件的状态,你必须在传递它之前将它绑定到函数。
class Parent extends React.Component {
callMeMaybe(param) {
console.log(param)
}
render(){
return (
<TheChild callMeMaybe={this.callMeMaybe.bind(this)} />
)
}
}
class TheChild extends React.Component {
render(){
return (
<div>
<button onClick={ event => {
this.props.callMeMaybe("message from child") }
}>Send a Message to Parent </button>
</div>
)
}
}
这是一个jsfiddle供你玩。单击按钮后检查控制台。
答案 1 :(得分:0)
使用参数从子句面调用绑定函数。
const IncrementOne = props => (
<button onClick={() => props.increment(1)}>
Increment 1
</button>
);
const IncrementTwo = props => (
<button onClick={() => props.increment(2)}>
Increment 2
</button>
);
const IncrementX = props => (
<button onClick={() => props.increment(props.x)}>
Increment {props.x}
</button>
);
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = { counter: 0 };
this.increment = this.increment.bind(this);
}
increment(amount) {
let counter = this.state.counter + amount;
this.setState({ counter });
}
render() {
return (
<div>
<div>
{this.state.counter}
</div>
<IncrementOne increment={this.increment} />
<IncrementTwo increment={this.increment} />
<IncrementX increment={this.increment} x={3} />
<IncrementX increment={this.increment} x={4} />
</div>
);
}
}
ReactDOM.render(<Parent />, document.getElementById('app'));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
&#13;