从外部上下文访问React组件函数

时间:2016-05-16 13:46:12

标签: reactjs ecmascript-6 react-jsx jsx

我有Class1,它只是Class2的容器。我在Test中声明了Class1个组件。现在,我想将Test作为参数传递给Class2

是否可以在我发表评论的位置Test内访问Class2组件的上下文?

export default class Class1 extends React.Component {
    render() {
        let test = (<Test />);

        return (
            <Class2 test={test} />
        );
    }
}

export default class Class2 extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        let { test } = this.props;

        // how to access Test class context?
        test.setValue("WHERE IS MY CONTEXT?");

        return (
            <div>{ test }</div>
        );
    }
}

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

        this.state = {
            value: ""
        };
    }

    setValue(val) {
        this.setState({
            value: val
        });
    }

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

我试图在网上找到一些内容并检查test对象,但我什么也没找到......当我尝试直接访问test.props时,我得到一个props的React错误是只读的,无法访问...

2 个答案:

答案 0 :(得分:1)

使用道具代替州:

let { test } = this.props;

<div>{ React.cloneElement(test, {value: "Hello World"}) }</div>

Test

<div>{ this.props.value }</div>

PS:Context means something else in React

答案 1 :(得分:0)

一个完整的例子:

class Class1 extends React.Component {
    render() {
        return (
            <Class2>
                <Test />
            </Class2>
        );
    }
}

class Class2 extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div>
                {React.cloneElement(this.props.children, {text: "WHERE IS MY CONTEXT?"})}
            </div>
        );
    }
}

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

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

JSFiddle