如何创建一个reactjs组件,它将使用另一个组件呈现props数据.
例如,我有一句话说“你好,这是{{name}}.你好吗.”现在我想用reactjs组件替换名称.
当我尝试用它显示为[对象对象]的组件替换名称时.
例如,我有一句话说“你好,这是{{name}}.你好吗.”现在我想用reactjs组件替换名称.
当我尝试用它显示为[对象对象]的组件替换名称时.
第一编辑:
var sentence = "Hello guys this is {{name}}. How are you."; var tag_values = {'name': 'any Name'}
TagBox将使用sentence和tag_value作为props,并用Tag组件替换标签.并渲染它
var TagBox = React.createClass({ render: function(){ // replacing the tags with Tag component this.props.sentence = this.props.sentence.replace(tags_values['name'],<Tag \>) return( <div> {this.props.sentence} //Issue: This will Print as "Hello guys this is [Object Object]. How are you." // But this should print as "This will Print as Hello guys this is any Name. How are you." // After clicking on "any Name" it should be replaced with input. </div> ); } })
标签组件将双击输入框替换标签.并再次使用输入数据替换输入框.
这可以使用状态来完成.
var Tag = React.createClass({})
好的,假设这是一个你输入的字符串,你需要创建一个数组.
原文链接:https://www.f2er.com/react/300715.htmlvar parts = str.split(/\{\{|\}\}/g); // => ["Hello guys this is ","name",". How are you."]
奇数项是文字字符串,偶数部分是括号之间的东西.
现在我们将创建一个名为mapAlternate的辅助函数.它需要一个函数来调用奇数元素,以及一个函数来调用我们数组中的偶数元素.
function mapAlternate(array,fn1,fn2,thisArg) { var fn = fn1,output = []; for (var i=0; i<array.length; i++){ output[i] = fn.call(thisArg,array[i],i,array); // toggle between the two functions fn = fn === fn1 ? fn2 : fn1; } return output; }
现在我们可以在组件中执行以下操作:
render: function(){ var parts = str.split(/\{\{|\}\}/g); // render the values in <strong> tags var children = mapAlternate(parts,function(x){ return <span>{x}</span>; },function(x){ return <strong>{x}</strong> }); return <div>{children}</div>; }
这给了我们:“大家好,这就是名字.你好吗?”