Javascript ReactJS向子组件添加回调函数
我想将回调附加到已创建的react组件,这可能吗 这是我的包装器类,我想从现有子类调用Javascript ReactJS向子组件添加回调函数,javascript,reactjs,Javascript,Reactjs,我想将回调附加到已创建的react组件,这可能吗 这是我的包装器类,我想从现有子类调用callbackToCall: import React from 'react'; class MyComponent extends React.Component { callbackToCall() { console.log("callback called."); } render() { const {children} = th
callbackToCall
:
import React from 'react';
class MyComponent extends React.Component {
callbackToCall() {
console.log("callback called.");
}
render() {
const {children} = this.props;
// Here I want to attach the callback to call
// E.g. children.props.callback = callbackToCall;
return (
<div>
MyStuff
{children};
</div>
);
}
}
从“React”导入React;
类MyComponent扩展了React.Component{
callbackToCall(){
log(“调用回调”);
}
render(){
const{children}=this.props;
//这里我想把回调附加到call
//例如,children.props.callback=callbackToCall;
返回(
糠秕
{儿童};
);
}
}
子类,它没有对容器类的任何回调:
import React from 'react';
class Child extends React.Component {
render() {
return <button onClick={this.props.callback}>Click me</button>
}
}
从“React”导入React;
子类扩展了React.Component{
render(){
返回单击我
}
}
这是我的组件的调用,我不知道如何引用回调:
<MyComponent>
<Child /* Here I cannot set the callback callback={...callbackToCall}*/ />
</MyComponent>
考虑到
MyComponent
是一个包装器,它接受唯一的子项,并且应该为它提供回调
道具,它应该是:
class MyComponent extends React.Component {
...
render() {
const child = React.cloneElement(
React.Children.only(this.props.children),
{ callback: this.callbackToCall }
);
return (
<div>
MyStuff
{child};
</div>
);
}
}
通过这种方式,
MyComponent
可以额外接受儿童用于其他目的,如…
这可能对您有用,特别是关于React的第二个答案。我不确定我是否理解得很好。顺便问一下,如果您将MyComponent创建为HOC或渲染道具?回调将是您传递给整个包装器组件的道具,因为包装器组件不知道它将获得哪些子级。这是从包装器组件本身外部完成的。未知子组件应该能够通过调用一些回调来通知包装器有关更改。我已经考虑过了,但是是否有必要克隆子元素?@KevinWallis是的,因为您提供的是React元素,而不是MyComponent的组件。若你们需要修改现有元素的道具,你们需要克隆它。另一种不需要克隆的模式是使MyComponent接受组件,
。因此,您可以在MyComponent render中像
一样返回它。这两种模式都在React world中使用。感谢您的详细回答,请您进一步描述上述答案的第二种方法好吗?:)
class MyComponent extends React.Component {
...
render() {
return (
<div>
MyStuff
<this.props.component callback={this.callbackToCall}/>
{this.props.children};
</div>
);
}
}