我有一个带有触发元素的组件,触发元素是一个像下面这样的 react 组件
const TriggerComponent = () => <div> trigger example </div>
<MyComponent trigger={<TriggerComponent />} />
在MyComponent类内部,我想通过cloneElement或creatElement API向触发元素添加ref属性,当然,根据react文档,我无法向功能组件添加ref属性。所以我的想法是将函数组件转换为类?
如果您对如何实现这个想法有任何想法,请告诉我?
最佳答案
将 ref 添加到有状态组件子组件的最佳方法是创建一个类 Ref 并将函数组件作为子组件注入(inject),如下所示:
class Ref extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
const { innerRef } = this.props;
if (innerRef) innerRef(findDOMNode(this));
}
render() {
const { children } = this.props;
return React.Children.only(children);
}
}
我们可以向函数组件添加引用。
const Trigger = ()=> <button> trigger </button>
const RefTrigger = () => <Ref innerRef={this.setRef}><Trigger/></Ref>
关于javascript - 将函数 react 组件转换为 react 类以添加 ref 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48842537/