javascript - 设置子项的内联样式

标签 javascript reactjs

我正在尝试为 React 中的子项设置一些内联样式。我有这个确实有效,有点像:

var App = React.createClass({
  render: function() {
    var children = React.Children.map(this.props.children, function(child, i) {
      child.props.style.width = '100px'
    })
    return (
      <div>{children}</div>
    )
  }
})

但是,如果我尝试在状态更改时更改样式,样式将保持不变。尝试这样的事情时,您可以很容易地看到这一点:( fiddle :http://jsfiddle.net/9UvWL/)

var World = React.createClass({
    getInitialState: function() {
        return { width: 0 }
    },
    componentDidMount: function() {
        this.setState({ width: 100 })
    },
    componentDidUpdate: function() {
        console.log(this.getDOMNode().innerHTML);
    },
    render: function() {
        var width
        var children = React.Children.map(this.props.children, function(child, i) {
            width = i*this.state.width
            console.log('Setting width: '+width);
            child.props.style = {width: (i*this.state.width)+'px'}
            return child
        }, this)
        return <div>{children}</div>
    }
 })

var Hello = React.createClass({
    render: function() {
        return (
            <World>
                <div>1</div>
                <div>1</div>
            </World>
        )
    }
})

React.renderComponent(<Hello />, document.body);

它会记录宽度已更改,但 props.style 未按预期工作。并且使用 child.setProps() 将抛出“Invariant Violation: replaceProps(...): Can only update a mounted component.”。是否有另一种将内联样式更改为子项的“ react 方式”?

最佳答案

您正在直接修改每个 child 的 props 对象,这绕过了 React 的部分更新机制。我们很快就会让这成为不可能。

在这种情况下,您想在 World 组件的渲染函数中使用 cloneWithProps

var children = React.Children.map(this.props.children, function(child, i) {
    width = i*this.state.width;
    console.log('Setting width: '+width);
    return React.addons.cloneWithProps(child, {style: {width: width + 'px'}})
}, this)
return <div>{children}</div>

cloneWithProps 创建组件的新副本并合并其他 Prop 。您应该使用此模式来确保为 React 提供它需要知道何时更新的所有提示。

这是您的示例:http://jsfiddle.net/zpao/Tc5Qd/

关于javascript - 设置子项的内联样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24474721/

相关文章:

javascript - 我可以在 text.replace 函数的第二部分中使用正则表达式的部分吗?

javascript - 向 ckeditor 添加占位符

node.js - 一个 Package.json 来管理 Node 和 React 依赖项

css - 将自定义样式应用于 react 选择和最佳实践

javascript - 如何使用dimple.js按不同数据行对y轴进行排序

javascript - 一开始如何不启用切换类?

javascript - Onsen-ui Carousel 属性自动播放不起作用

javascript - 在 React 中将状态数组从一个组件传递到另一个组件

reactjs - React 和 Tailwind CSS 中的 SVG — 填充 : "currentColor" not working

javascript - 如何使用 onClick 获取数组?