我必须在父组件中运行子组件方法。这不是官方的,但我需要为复杂的代码运行它......我尝试使用 refs
但它在父组件中不起作用。出现以下错误。
Cannot read property 'renderSetup' of undefined
父组件:
class Parent extends Component {
constructor(props) {
super(props);
this._renderSetup = this._renderSetup.bind(this);
}
componentDidMount() {
this._renderSetup();
}
_renderSetup() {
this.refs.Child.renderSetup();
}
render() {
return (
<Child ref={Child} />
)
}
子组件
class Child extends Component {
constructor(props) {
super(props);
this.renderSetup = this.renderSetup.bind(this);
}
renderSetup = () => {
// complicated code
}
最佳答案
ref
属性是一种特殊属性,您无法通过 props
访问它。要在组件上使用 ref
,您可以用 React.forwardRef()
将其包装起来。 :
const { Component, createRef } = React;
class _Child extends Component {
constructor(props, ...args) {
super(props, ...args);
if(props.forwardedRef) {
props.forwardedRef.current = {
renderSetup: this.renderSetup
};
}
}
renderSetup = () => {
console.log('renderSetup');
}
render() {
return <div>Child</div>;
}
}
const Child = React.forwardRef((props, ref) => (
<_Child {...props} forwardedRef={ref} />
));
class Parent extends Component {
childRef = createRef();
componentDidMount() {
this._renderSetup();
}
_renderSetup = () => {
if(this.childRef.current) {
this.childRef.current.renderSetup();
}
}
render() {
return (
<Child ref={this.childRef} />
)
}
}
ReactDOM.render(
<Parent />,
root
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
关于javascript - 无法在父组件中运行子组件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59895234/