在ReactJs中,通过循环字符串
动态更改节点元素的颜色,尝试从React.Children.map
更改字符串变量,然后React.cloneElement
更改颜色。我的主页上有一个标题。我想更新标题字符串中每个字符的节点颜色。试图做这种方式,但得到恩错误:Cannot read property 'colorString' of undefined
在ReactJs中,通过循环字符串
const LetterStyle = React.createClass({
colorString: function(value){
this.setState({color: "green"});
},
render: function(){
const colorArray = []
var childrentWithProps = React.Children.forEach(this.props.children, (child, i) => {
for (var i=0; i<child.length; i++){
return React.Children.map(child[i], function(content, i) {
if(content !== " "){
React.cloneElement(content, { colorString: this.colorString })
}
});
}
})
return(
<h1 className="lead" ref="lead">
<span>{childrentWithProps}</span>
</h1>
);
}
});
看起来你正在失去你所得到的线React.cloneElement(content, { colorString: this.colorString })
尝试定义var that = this
时间this
参考;在render function() {
像
render: function()
{
var that = this;
const colorArray = [] to preserve the properties of `this`.
,改变线 React.cloneElement(content, { colorString: that.colorString })
而且之后,我建议阅读let
之间的差异,var
和const
。在ES6语法中,通常不需要var
,将其与const
和let
混合可能会引起混淆。了解更多关于这里的区别:
What's the difference between using "let" and "var" to declare a variable?
这是我第一次看到从React Top-Level API .MAP和foreach的实现。它们与本地JavaScript表兄弟的用法不同。
您的代码有几个问题。
第一问题引起你的错误:
后者状态React.Children.map
和React.Children.forEach
带有两个参数,首先是孩子的一个键控片段或阵列,第二个是一个回调其的文档只有参数是它将在React.Children.forEach
和React.Children.map
调用中设置的值。他们的签名如下:
React.Children.forEach(children, function[(thisArg)])
React.Children.map(children, function[(thisArg)])
然后,解决方案是不传入参数,而是传入任一调用以清除错误。
作为一个例子,你得到的.map
电话是这样的:
return React.Children.map(child[i], function(this){
if (content !== " "){
React.cloneElement(content, { colorString: this.colorString });
}
});
第二个问题值得一提的是:
您已经使用这里的forEach这将有效遍历this.props.children
数组。
它内部引用当前值在child
上迭代,并对该元素运行for循环以转到您的.map
调用。
这看起来对于您的应用程序来说看起来不正确,因为child
很可能代表单个组件或React元素,而不是再次循环的数组。
解决方法:使用for循环或在foreach这里,但不能同时