reactjs - 如何在运行时设置/重置属性以响应元素
问题描述
好的。让我们把这个问题变得很简单。
我有一个名为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"/>);
}
但这不是我想要完成的方式。我想通过从方法返回的对象来设置它。可能吗 ?
解决方案
我发现React.cloneElement
可以克隆对象并用它插入新的道具。
let GreenText = React.cloneElement(this.getGreenText(),{
text : 'I am green text'
});
完整的工作源代码可以在这里找到:Gist
推荐阅读
- multithreading - 这个线程池代码是否尝试双重执行任务?
- java - 在 Android OS 中的 DatePicker 中,Harmony OS 中 setFirstDayOfWeek() 的替代方法是什么?
- path - HAProxy - 无法更改后端服务器中的路径
- php - PHPCS 的 Git Pre-Commit 钩子在 Laravel 的 Windows 中给了我错误
- r - Shinyapps 部署错误:应用程序依赖于包“dplyr”但未安装
- python - 查找数据框中的所有转换
- react-native - 如何使用样式在本机反应中创建甘特图
- visual-studio - 在 VS Toolbox 中以不同的 DisplayName 显示组件
- apache-flink - StreamTableEnvironment 是否能够针对批处理流运行?
- visual-studio-code - 检查项目文件夹中所有资产的大小写敏感及其在程序中的声明