我有一个React JSX元素,我想迭代它的子节点,对其中的每个字符串元素执行replace(或任何其他操作),并返回新的,修改过的JSX元素。例如:
private void SendDailyEmails(DateTime today)
{
today = DateTime.Now;
string recipient = "Test1@stanleytests.co.za,Test2@stanleytests.co.za";
string[] emailTo = recipient.Split(',');
for (int i = 0; i < emailTo.GetLength(0); i++)
{
var emailObject = new EmailObject
{
To = emailTo[i],
Cc = "me@stanleytests.co.za",
Subject = "Daily Mail",
Body = "Good morning, <br/><br/> This email is sent to you: <strong> "please be adviced" </strong> <br/><br/>Regards"
};
_emailService.SendEmail(emailObject);
}
}
但是,var element = <span>Text { var1 } Text2 text3 { var2 }</span>;
var modifiedChildren = [];
element.props.children.forEach(function(child){
if(typeof child === 'string') {
var modifiedChild = child.replace('a', 'b');
modifiedChildren.push(modifiedChild);
}
}
var modifiedElement = element;
modifiedElement.props.children = modifiedChildren;
是只读的,这使我无法执行此操作。但这也不是我想要的,我只想制作带有修改过的孩子的新JSX元素。
在保持ReactJS思维方式的同时实现这一目标的方法是什么?
答案 0 :(得分:2)
您可以使用React.Children.Map
来迭代组件的子项。
React.Children.map(children, function[(thisArg)])
有些事情是这样的:
renderChildren() {
return React.Children.map(this.props.children, child => {
React.cloneElement(child, {
newProp: this.props.name
})
})
}
要不可改变地改变您可以使用的元素React.cloneElement
React.cloneElement(
element,
[props],
[...children]
)
https://reactjs.org/docs/react-api.html#cloneelement https://reactjs.org/docs/react-api.html#reactchildren
检查此link以获取更多信息