Reactjs如何将react组件插入到字符串中然后呈现

如何创建一个reactjs组件,它将使用另一个组件呈现props数据.
例如,我有一句话说“你好,这是{{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({})
好的,假设这是一个你输入的字符串,你需要创建一个数组.
var 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>;
}

这给了我们:“大家好,这就是名字.你好吗?”

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...