[英]Passing event and props from child to parent in react
我已经开始将一些代码拆分为presentational/container
组件,我想在child/presentational
组件中调用一个函数,并将事件和某种道具传递回父组件。
家长:
class Parent extends Component{
constructor(props) {
super(props);
this.state = {}
this.reroll = this.reroll.bind(this);
}
test(key, e){
console.log(key, e)
}
render() {
return <Child test={()=>this.test} />
}
}
孩子:
var Child = () => {
return (
<select onChange={props.test('test-key')}>
<option value='1'> Option 1 </option>
//etc...
</select>
)
}
通常,当我将所有代码放在一处时,我会像这样编写 onChange 函数。
<select onChange={props.test.bind(this, 'test-key')}>
但是在孩子中绑定 this 会导致它不再起作用。 传递给此函数的其他道具不会返回给父级。 有什么方法可以写这个,以便我可以取回“测试密钥”?
第一:您应该尽可能避免在渲染中绑定函数,因为它会导致每次调用渲染时都会创建一个新函数。 在你的情况下,你可以很容易地避免它,比如
使用箭头函数定义测试函数
test(key, e){
console.log(key, e)
}
然后在父类中使用它
<Child test={this.test} />
现在在子组件中
test = (e) => {
this.props.test('test-key', e)
}
<select onChange={this.test}>
您需要将函数调用放在onChange
事件的回调中。
<select onChange={()=>props.test('test-key')}>
通过这种方式,您也可以传递event
对象。
<select onChange={(event)=>props.test(event,'test-key')}>
来这里的任何人都试图为功能组件找到相同的东西。 我这里有一个例子。 父组件示例:
<SaveButton
newsArticleId="someId"
onClickCallback={handleSaveNote}
/>
const handleSaveNote = (e, articleId) => {
const event = e || window.event;
event.preventDefault();
setArticleId(articleId);
....code removed
};
子组件示例:
const SaveButton = ({ newsArticleId, onClickCallback }) => {
return (
<button
id={newsArticleId}
className='btn btn-sm btn-primary'
type='button'
data-toggle='dropdown'
aria-haspopup='true'
aria-expanded='false'
onClick={(e) => onClickCallback(e, newsArticleId)}
>
Save
</button>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.