javascript - React - 你可以变异修改 this.props.children 来动态(以编程方式)添加子组件

标签 javascript facebook reactjs

根据 fb 文档,this.props.children 是一个不透明的数据结构,不应直接操作。

事实上,文档说我们应该使用 React.Children 中的库函数。

看看库函数,它们都是 getter,这让我相信我们不应该改变 this.props.children

这是真的吗?我们可以改变 this.props.children (例如动态插入组件等)吗?

谢谢!

最佳答案

您不能(或不应该)直接改变子级。但是,您可以通过映射“修改”其输出:

const Hydrogen = props => (<div>{props.weight}</div>);
const Oxygen = props => (<div>{props.weight}</div>);

const Water = props => (
    <div className='water'>
    {React.Children.map(props.children, child => (
        React.cloneElement(child, {
            weight: props.weight / React.Children.count(props.children)
        })
    ))}
    </div>
);

const WaterBalloon = props => (
    <div className='water-balloon'>
        <Water weight={3}>
            <Hydrogen />
            <Hydrogen />
            <Oxygen />
        </Water>
    </div>
);

在这里,我“修改”了传递给 Water 的子项,将重量属性传递给它们。

如果您需要“添加/删除”的能力,也许您应该考虑重新设计,维护一个“数据”数组,然后从该数据填充组件:

https://jsfiddle.net/814jze3z/

const Item = props => (
    <li>{props.time}</li>
);

class List extends React.Component
{
    constructor() {
        super();
        this.state = {
            items: []
        };

        this.addItem = this.addItem.bind(this);
        this.removeItem = this.removeItem.bind(this);
    }

    addItem() {
        let item = {
            id: this.state.items.length + 1,
            time: +new Date()
        };

        this.setState({
            items: this.state.items.concat([item])
        });
    }

    removeItem() {
        this.setState({
            items: this.state.items.concat().splice(1)
        });
    }

    render() {
        return (
            <div>
                <button onClick={this.addItem}>Add Item</button>
                <button onClick={this.removeItem}>Remove Item</button>
                <ul className='list'>
                {this.state.items.map(item => (
                    <Item key={item.id} time={item.time} />
                ))}
                </ul>
            </div>
        );
    }
}

关于javascript - React - 你可以变异修改 this.props.children 来动态(以编程方式)添加子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41809722/

相关文章:

javascript - 如何根据所选元素的高度设置父级的高度

javascript - 如何使用 html、php、css 和 javascript 上传 .txt 文件并保存到另一个目录?

javascript - 对象未定义,不知道为什么

Facebook 积分 : Obtaining the number of credits

javascript - Formik - chrome 自动填充密码输入问题

javascript - 如何设置backrid中单元格的高度和宽度

facebook - 获取给定 URL 的 Facebook 点赞/分享计数

facebook - meteor 登录外部服务 : how to get profile information?

performance - React - 延迟繁重的子组件渲染

reactjs - 未处理的拒绝(SecurityError): The operation is insecure. 在新的 create-react-app 项目上