【问题标题】:Invoke function from React component declared as variable从声明为变量的 React 组件调用函数
【发布时间】:2016-05-12 12:39:45
【问题描述】:

React 组件在变量中给出时如何调用该组件的函数?我有一个ParentTest 类传递给Child 组件,而这个孩子想要更改Test 中的某些内容。

export class Parent extends React.Component {
    render() {
        let test = (<Test />);
        return (<Child tester={test} />);
    }
}

export class Child extends React.Component {
    render() {
        this.props.tester.setText("qwerty"); // how to invoke setText, setState or something like that?
        return ({this.props.tester});
    }
}

export class Test extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            text: this.props.text || ""
        };
    }

    setText(text) {
        this.setState({ text: text });
    }

    render() {
        return (<div>{this.state.text}</div>);
    }
}

【问题讨论】:

  • 您想在Test 中更改什么?您可以将要更改的所有内容作为道具传递并立即渲染。不需要函数。
  • 我想在Child 中传递一些东西,其中Test 只是从Parent 传递的对象的引用。我不能简单地做this.props.tester.text = "sth"

标签: reactjs ecmascript-6 react-jsx jsx


【解决方案1】:

我认为你应该考虑 React 组件的生命周期。
请尝试下面的代码(我刚刚添加了日志记录),并仔细观察日志。

export class Parent extends React.Component {
    render() {
        let test = (<Test />);
        return (<Child tester={test} />);
    }
}

export class Child extends React.Component {
    render() {
        console.log("Child render"); // <= logging added!
        // this.props.tester.setText("qwerty"); 
        // What kind of object is 'this.props.tester(= <Test />)' here???
        return ({this.props.tester});
    }
}

export class Test extends React.Component {
    constructor(props) {
        super(props);
        console.log("Test constructor"); // <= logging added!
        this.state = {
            text: this.props.text || ""
        };
    }

    setText(text) {
        // this.setState({ text: text });
        // this is another problem. We cannot call setState before mounted.   
        this.state.text= text;  
    }

    render() {
        return (<div>{this.state.text}</div>);
    }
}

如果是这样,您将看到 2 个重要事实。

  1. 当您调用“setText”时,“Test”组件尚未实例化。
    我们如何调用未实例化的对象方法?不能!
  2. 这意味着“this.props.tester”不是“Test”组件的实例。

但是,如果您真的想执行您的代码,请像这样修改 Child.render。

render() {
    var test = new Test({props:{}});
    // or even this can work, but I don't know this is right thing
    // var test = new this.props.tester.type({props:{}});
    test.setText("qwerty");
    return test.render();
}

但我认为这不是一个好方法。

从另一个角度来看,人们可能会想出这样的想法,

render() {
    // Here, this.props.tester == <Test />
    this.props.tester.props.text = "qwerty";
    return (this.props.tester);
}

当然这是不可能的,因为 'this.props.tester' 是 Child 的只读属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-22
    相关资源
    最近更新 更多