我正在尝试为 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 提供它需要知道何时更新的所有提示。
关于javascript - 设置子项的内联样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24474721/