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

前端之家收集整理的这篇文章主要介绍了Reactjs如何将react组件插入到字符串中然后呈现前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何创建一个reactjs组件,它将使用另一个组件呈现props数据.
例如,我有一句话说“你好,这是{{name}}.你好吗.”现在我想用reactjs组件替换名称.
当我尝试用它显示为[对象对象]的组件替换名称时.

第一编辑:

  1. var sentence = "Hello guys this is {{name}}. How are you.";
  2.  
  3. var tag_values = {'name': 'any Name'}

TagBox将使用sentence和tag_value作为props,并用Tag组件替换标签.并渲染它

  1. var TagBox = React.createClass({
  2. render: function(){
  3. // replacing the tags with Tag component
  4. this.props.sentence = this.props.sentence.replace(tags_values['name'],<Tag \>)
  5. return(
  6. <div>
  7. {this.props.sentence} //Issue: This will Print as "Hello guys this is [Object Object]. How are you."
  8. // But this should print as "This will Print as Hello guys this is any Name. How are you."
  9. // After clicking on "any Name" it should be replaced with input.
  10. </div>
  11. );
  12. }
  13. })

标签组件将双击输入框替换标签.并再次使用输入数据替换输入框.
这可以使用状态来完成.

  1. var Tag = React.createClass({})
好的,假设这是一个你输入的字符串,你需要创建一个数组.
  1. var parts = str.split(/\{\{|\}\}/g);
  2. // => ["Hello guys this is ","name",". How are you."]

奇数项是文字字符串,偶数部分是括号之间的东西.

现在我们将创建一个名为mapAlternate的辅助函数.它需要一个函数调用奇数元素,以及一个函数调用我们数组中的偶数元素.

  1. function mapAlternate(array,fn1,fn2,thisArg) {
  2. var fn = fn1,output = [];
  3. for (var i=0; i<array.length; i++){
  4. output[i] = fn.call(thisArg,array[i],i,array);
  5. // toggle between the two functions
  6. fn = fn === fn1 ? fn2 : fn1;
  7. }
  8. return output;
  9. }

现在我们可以在组件中执行以下操作:

  1. render: function(){
  2. var parts = str.split(/\{\{|\}\}/g);
  3.  
  4.  
  5. // render the values in <strong> tags
  6. var children = mapAlternate(parts,function(x){ return <span>{x}</span>; },function(x){ return <strong>{x}</strong> });
  7.  
  8. return <div>{children}</div>;
  9. }

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

猜你在找的React相关文章