使用React,如何访问子组件的渲染返回值

时间:2019-03-22 15:31:56

标签: reactjs

我有一个React Component来替换字符串或字符串数​​组中的某些内容,并且我还有另一个Component可以做类似的事情。两者都在其render()方法中返回字符串数组。现在,我想将它们组合起来,并将第二个组件的输出用作第一个组件的输入。

这是我要实现的目标的非常简化的示例:

class Container extends React.Component {
    render() {
        return ['Hello', 'World'];
    }
}

class Enhancer extends React.Component {
    render() {
        // Get actual content of the children,
        // not the React element.
        // How do I do that?
        const content = this.props.children;

        return content.splice(1, 0, 'Dear');
    }
}

render(
    <Enhancer>
        <Container />
    </Enhancer>
)

// Expected: HelloDearWorld

我已经搜索了Web和React的文档,但是找不到解决方法。是否可以在React中访问子元素的实际值?

谢谢!

编辑:解决方案!

function withSpecialContent(WrappedComponent, content) {
    return class extends React.Component {
        render() {
            return <WrappedComponent>
                { content }
            </WrappedComponent>;
        }
    }
}

class Enhancer extends React.Component {
    render() {
        return content.splice(1, 0, 'Dear');
    }
}

render(
    withSpecialContent(Enhancer, ['Hello', 'World']);
)

// Result: HelloDearWorld

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:0)

所以,我认为您需要Container成为输入和Enhancer组件之间的“中间”。类似于以下内容:

class Enhancer extends React.Component {
    render() {
        return (
            this.props.arrStr.map((str, index) => {
                /* Here you have the computation made from `Enhancer`. */
                return <p key={index}>Dear {str}</p>;
            })
        );
    }    
}

class Container extends React.Component {
    render() {
        /* Perform operations on the strings. */
        const processedStrings = this.props.arrStr.map(str => str + ", how are you?");
        
        /* You pass the processed strings to the enhancer. */
        return <Enhancer arrStr={processedStrings} />;
    }
}

ReactDOM.render(<Container arrStr={["Foo", "Bar", "Miz"]} />, document.getElementById('root'));
@import url(https://fonts.googleapis.com/css?family=Montserrat);

body {
    font-family: 'Montserrat', sans-serif;
}
<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>