首页 > 解决方案 > 如何在运行时设置/重置属性以响应元素

问题描述

好的。让我们把这个问题变得很简单。

我有一个名为ColorText.

class ColorText extends React.Component{
  render(){
    return (<Text style={{color:this.props.color}}>{this.props.text}</Text>);
  }
}

当我打电话时

<ColorText color="red" text="I am red text"/>

有用。

在此处输入图像描述

现在,我有一个返回ColorText这样的函数

 getGreenText = () => {
    return (<ColorText text="Default text" color="green"/>);
 }

我想像这样在运行时重置文本属性

const GreenText = this.getGreenText();
GreenText.props.text = "I am green text";

它不起作用。并打印默认文本

所以,这是我的问题。是否可以在运行时设置/重置反应组件的属性?正确的方法是什么?

注意:我用谷歌搜索了很多,找不到任何积极的东西。如果您对问题有任何疑问,请在评论中问我。完整的源代码可以从这里获得

编辑:

我知道这可以通过简单地将变量传递给这样的方法来完成

getGreenText = (text) => {
    return (<ColorText text={text || "Default text"} color="green"/>);
}

但这不是我想要完成的方式。我想通过从方法返回的对象来设置它。可能吗 ?

标签: reactjsreact-native

解决方案


我发现React.cloneElement可以克隆对象并用它插入新的道具。

let GreenText = React.cloneElement(this.getGreenText(),{
    text : 'I am green text'
});

完整的工作源代码可以在这里找到:Gist


推荐阅读