【问题标题】:Manipulating JSX element's children collection操作 JSX 元素的子集合
【发布时间】:2018-08-21 16:48:55
【问题描述】:

我有一个 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;

但是,element.props.children 是只读的,这使我无法这样做。但这也不是我想要的,我只是想用修改的子元素制作新的 JSX 元素。

在保持 ReactJS 思维方式的同时实现这一目标的方法是什么?

【问题讨论】:

    标签: javascript arrays reactjs jsx


    【解决方案1】:

    您可以使用React.Children.Map 来迭代组件的子级。

    React.Children.map(children, function[(thisArg)])
    

    类似这样的事情:

    renderChildren() {
      return React.Children.map(this.props.children, child => {
        React.cloneElement(child, {
          newProp: this.props.name
        })
      })
    }
    

    要不可变地更改您可以使用的元素,React.cloneElement

    React.cloneElement(
      element,
      [props],
      [...children]
    )
    

    https://reactjs.org/docs/react-api.html#cloneelement https://reactjs.org/docs/react-api.html#reactchildren

    查看link了解更多信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-21
      • 2019-12-25
      • 2020-07-05
      • 2012-12-01
      • 1970-01-01
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多