Reactjs 如何在React+;派一名助手
我遵循这一点,但它没有说明如何向函数传递参数 在他们身上有他们的孩子Reactjs 如何在React+;派一名助手,reactjs,Reactjs,我遵循这一点,但它没有说明如何向函数传递参数 在他们身上有他们的孩子 <Button onClick={this.props.action} /> handler(id) { this.setState({ messageShown: true, id : id }); } 处理程序(id){ 这是我的国家({ 消息显示:是的, id:id }); } 如果我想随它一起发送一
<Button onClick={this.props.action} />
handler(id) {
this.setState({
messageShown: true,
id : id
});
}
处理程序(id){
这是我的国家({
消息显示:是的,
id:id
});
}
如果我想随它一起发送一个值(比如某个id或其他东西),会发生什么
我试着去做
<Button onClick={() => this.props.action(1)} />
this.props.action(1)}/>
但是,我的“状态”是未定义的。如果没有完整的代码示例,很难判断出哪里出了问题,但是您尝试做的肯定是可能的。这里有一个有效的例子
类父级扩展React.Component{
建造师(道具){
超级(道具)
//将此上下文绑定到处理程序函数
this.handler=this.handler.bind(this);
//设定一些状态
此.state={
消息显示:false
};
}
//此方法将被发送到子组件
处理程序(id){
这是我的国家({
消息显示:是的,
id:id
});
}
//呈现子组件并将处理程序作为值设置action属性
render(){
console.log(this.state);
返回(
{this.state.id}
);
}
}
子类扩展了React.Component{
render(){
返回(
{/*该按钮将执行父组件设置的处理程序函数*/}
这个.props.action(1)}>按钮
)
}
}
ReactDOM.render(,document.getElementById('main'))代码>
要实现您想要的功能,您应该在子组件中调用调用调用传递函数的函数。在这种情况下,您可以传递任何想要的参数
让我们编码吧
您的父组件将是:
class Parent extends React.Component {
constructor(props) {
super(props)
// Bind the this context to the handler function
this.handler = this.handler.bind(this);
// Set some state
this.state = {
messageShown: false,
id: -1 // initialize new state property with a value
};
}
// This method will be sent to the child component
handler(id) {
this.setState({
messageShown: true,
id: id
});
}
// Render the child component and set the action property with the handler as value
render() {
return <Child action={this.handler} />
}
}
类父级扩展React.Component{
建造师(道具){
超级(道具)
//将此上下文绑定到处理程序函数
this.handler=this.handler.bind(this);
//设定一些状态
此.state={
消息显示:false,
id:-1//使用值初始化新状态属性
};
}
//此方法将被发送到子组件
处理程序(id){
这是我的国家({
消息显示:是的,
id:id
});
}
//呈现子组件并将处理程序作为值设置action属性
render(){
返回
}
}
您的子组件将是
class Child extends React.Component {
render() {
return (
<div>
{/* The button will execute the handler function set by the parent component, passing any parameter */}
<Button onClick={() => this.props.action(1)} />
</div>
)
}
}
类子级扩展React.Component{
render(){
返回(
{/*该按钮将执行父组件设置的处理程序函数,并传递任何参数*/}
this.props.action(1)}/>
)
}
}
希望这有帮助通常当调用回调函数后未定义this.state时,这是一个绑定问题。在父组件的构造函数中仔细检查处理程序函数是否绑定了该函数
this.handler = this.handler.bind(this);
有关绑定的更多信息:请提供完整的不工作示例(两个组件)。现在您粘贴的只是无效代码。