react组件中的绑定方法
Binding methods in react components
尝试将值绑定到组件函数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);
}
- 在D3.js中,有没有任何方法可以将x和y方向上的滚动事件绑定到平移svg
- react组件中的绑定方法
- 有没有比在app.js上绑定模块名称更好的方法来动态加载视图模型和视图以显示模态
- 在指令中绑定方法
- 有没有一种方法可以列出Ember.Object的所有绑定
- 对象文字方法上的Javascript绑定不起作用
- 关于JavaScript绑定方法
- Java 脚本中的 JavaScript 脚本中的绑定方法调用
- JavaScript 函数的绑定方法存在问题
- 何时有时将对象类型定义为将实例绑定方法镜像为构造函数上的静态实用程序函数很有用
- 在后台发生什么,以防止调用更改此对象的绑定方法
- 使用敲除foreach绑定绑定方法名称
- 绑定方法不起作用
- 在构造函数中绑定方法
- 如何将参数传递给绑定方法?绑定与匿名方法
- 单绑定方法
- Angularjs $scope变量内部的jquery绑定方法
- 有人能给我解释一下为什么绑定方法在这些例子中不起作用吗?
- 单元测试-使用应用、调用或绑定方法在JavaScript中注入依赖项
- 试图在作用域隔离的指令中运行绑定方法