cin*_*lug 3 javascript arrays jsx reactjs
我有一个 React JSX 元素,我想迭代它的子元素,对其中的每个字符串元素执行替换(或任何其他操作),并返回新的、修改后的 JSX 元素。例如:
var element = <span>Text { var1 } Text2 text3 { var2 }</span>;
var modifiedChildren = [];
element.props.children.forEach(function(child){
if(typeof child === 'string') {
var modifiedChild = child.replace('a', 'b');
modifiedChildren.push(modifiedChild);
}
}
var modifiedElement = element;
modifiedElement.props.children = modifiedChildren;
Run Code Online (Sandbox Code Playgroud)
然而,element.props.children它是只读的,这阻止了我这样做。但这也不是我想要的,我只想用修改后的子元素创建新的 JSX 元素。
在保持 ReactJS 思维方式的同时实现这一目标的方法是什么?
您可以用于React.Children.Map迭代组件的子组件。
React.Children.map(children, function[(thisArg)])
Run Code Online (Sandbox Code Playgroud)
像这样的事情:
renderChildren() {
return React.Children.map(this.props.children, child => {
React.cloneElement(child, {
newProp: this.props.name
})
})
}
Run Code Online (Sandbox Code Playgroud)
要一成不变地更改您可以使用的元素,React.cloneElement
React.cloneElement(
element,
[props],
[...children]
)
Run Code Online (Sandbox Code Playgroud)
https://reactjs.org/docs/react-api.html#cloneelement https://reactjs.org/docs/react-api.html#reactchildren
检查此链接以获取更多信息
| 归档时间: |
|
| 查看次数: |
1614 次 |
| 最近记录: |