react组件中的绑定方法

Binding methods in react components

本文关键字:绑定 方法 组件 react      更新时间:2023-09-26

尝试将值绑定到组件函数handleInput时出错:未捕获的类型错误:无法读取未定义的属性"bind"

但是,当我将input元素插入到render方法底部的return语句中时,它不会产生任何错误。我猜这与渲染方法的生命周期有关,但我不确定。

任何见解都值得赞赏。

至于代码的作用,它从this.props.info.text中检索一个字符串,并替换<=的所有实例var[0-9]=>使用html输入框,然后附加到div。在用户输入时,值会传播到父组件。

export default class Line extends React.Component {
 constructor() {
   super();
 }
 handleInput(id, e) {
   console.log(id);
   this.props.handleCode(e.target.value);
 }
 shouldComponentUpdate(){
   if (document.getElementById('otherClass').innerHTML.length == 0){
     return true;
   }
   return false;
 }
 render() {
   var id = this.props.id;
   let codeVal = "";
   let codeDiv = document.createElement('div');
   if (typeof(this.props.info) !== 'undefined') {
     //breaks here
     codeVal = this.props.info.text.replace(/<= var[0-9] =>/, '<input type="text" onInput=this.handleInput.bind(this,id)></input>');
     let index = codeVal.indexOf('<');
     let splits = [codeVal.slice(0, index), codeVal.slice(index)];
     codeDiv.innerHTML = "<div class='row'><div class='col-md-6'>"+splits[0]+"</div><div class='col-md-6'>"+splits[1]+ "</div></div>";
     document.getElementById('otherClass').appendChild(codeDiv);
   }
   return(
     <div id='otherClass'></div>
   );
 }
}

父代码:

export default class StateVal extends React.Component {
  handleCode(id, e){
    console.log("value propagated on user input");
    alert(e);
  }
  render() {
    return (
     <div className="col-md-6">
       <div className="card-block">
        < Line info={this.props.data.codeBody[0]} handleCode={this.handleCode} id={1} />
     </div>
   </div>
  );
}
}

编辑:想法是,如果我通过"int value=<=var0=>"之类的道具检索文本值,我如何将其转换为像这样的响应html输入标记

 int value = <input type='text' onInput=this.handleInput.bind(this, id)/>

然后在html 中渲染

只有当使用react从字符串生成HTML时,才能编写有效的HTML。

<input type='text' onInput=this.handleInput.bind(this, id)/>无效:onInput不是HTML有效的道具

使用react生成HTML的jsx字符串是需要babel的特殊情况。

我不认为您能够使用字符串在组件中即时插入jsx字符串,但可能还有其他解决方案。将字符串拆分为一个数组,并用一个jsx元素<...>代替匹配的字符串,而不是字符串代码"<../>"。这个jsx元素将具有与您的组件所需的函数绑定。我在这里找到了一个类似的解决方案:在JSX 中将字符串的一部分替换为标记

有一种正确的方法可以用react呈现字符串:

使用dangerouslySetInnerHTML将HTML作为字符串注入React中。受试者在此接受治疗

问候

您可以在末尾设置绑定关键字,如下所示,而不是您给出的示例。

onInput=this.handleInput(id).bind(this)

或者在这里调用这个方法,并在构造函数级别绑定它。

onInput=this.handleInput(id)
constructor() {
   super();
   this.handleInput=this.handleInput.bind(this);
 }