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

Access React component functions from outer context

我有 Class1,它只是 Class2 的容器。我在 Class1 中声明 Test 组件。现在我想将 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>
        );
    }
}

我试图在 Web 上找到一些东西并检查 test 对象,但我一无所获...当我尝试直接访问 test.props 时,我收到一个 React 错误 props 是只读的,无法访问...

使用道具代替状态:

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.

一个完整的例子:

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