gpt4 book ai didi

reactjs - react : Access child element with findDOMNode throws error

转载 作者:行者123 更新时间:2023-12-02 04:45:19 24 4
gpt4 key购买 nike

我有一个 Container 组件,它有几个 child 。

componentDidUpdate 上,我想更改样式属性。

似乎容器应该能够处理这个,而不是每个 child 自己处理。

问题,当尝试获取子节点的 Dom 节点时, react 会抛出错误。

  var childA = this.props.children[0];
React.findDOMNode(childA);
=> Uncaught Error: Invariant Violation: Element appears to be neither ReactComponent nor DOMNode (keys: )

编辑: ^^^ 是编写 React 的错误方式!

If your children need to do something, you should always try to pass it down from the top.

假设您有 3 种颜色:green,red,blue 并且您希望您的 child 以这种方式着色,但也许他们经常改变顺序。传下去

Parent = React.createClass({
renderChildren: function(){
var colors = ["red", "blue", "green"]

return React.Children.map(this.props,children, function(child, index){
// this returns a legit clone, adding one extra prop.
return React.cloneElement(child, {color: colors[index]});
})
},

render: function(){
return (
<div>{this.renderChildren()}</div>
)
}
})

Child = React.createClass({
render: function(){
return (<div style={{background: this.props.color}}>{'YOLO'}</div>)
}
})

最佳答案

在使用 React 时,您尝试做的不是推荐的做法。不要自己修改 DOM,使用 stateprops

子组件:

var ChildrenA = React.createClass({
render: function() {
return <div style={{color: this.props.color}}>Hello A</div>;
}
});

应用:

var App = React.createClass({
render: function() {
return (<div>
<div>Hello {this.props.name}</div>
<div>
<Container/>
</div>
</div>);
}
});

容器:

var Container = React.createClass({
getInitialState: function(){
return {color: "red"}
},
toggle: function(){
this.setState({
color: this.state.color == "red" ? "blue" : "red"
})
},
render: function() {
return (<div onClick={this.toggle}>
<ChildrenA color={this.state.color}/>
<ChildrenB/>
</div>);
}
});

JSFiddle:https://jsfiddle.net/3m8wLcgk/

你可能想看看这个:Thinking in React

关于reactjs - react : Access child element with findDOMNode throws error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33536261/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com