我有一个React组件,可以替换字符串或字符串数组中的一些内容,还有另一个可以执行类似操作的组件。在它们的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发布于 2019-03-22 15:33:39
发布于 2019-03-22 16:32:27
因此,我认为jsut需要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>
https://stackoverflow.com/questions/55303044
复制相似问题