如何设置/重置属性以在运行时反应元素

时间:2018-06-21 11:46:00

标签: reactjs react-native

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

我有一个名为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"/>

有效。

enter image description here

现在,我有一个函数可以像这样返回ColorText

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

并且我想像这样在运行时重置text属性

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

它不起作用。并显示默认文本

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

注意:我在Google上搜索了很多,找不到任何积极的信息。如果您有任何疑问,请在评论中问我。完整的源代码可以从here

获得

编辑:

我知道,只需将变量传递给像这样的方法就可以实现

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

但这不是我想要实现的方式。我想通过方法返回的对象进行设置。可能吗 ?

2 个答案:

答案 0 :(得分:1)

不能。这是设计使然。如果您尝试

GreenText.props.text = "I am green text";

由于道具是不可变的,因此会抛出错误。

您能否给出一个需要进行类似操作的用例?永远都不需要。


可能的解决方案

您可以简单地将文本作为参数传递,如下所示:

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

render() {
    const GreenText = this.getGreenText("I am green text");
    return (
        <View style={styles.container}>
            <ColorText color="red" text="I am red text"/>
            {GreenText}
        </View>
    );
}

如果您需要推迟文本的更新,则只需使用状态即可。

否则,您可以使用ref(请参阅:https://reactjs.org/docs/refs-and-the-dom.html)来实现所需的目标。

答案 1 :(得分:1)

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

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

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

相关问题