我是React的新手,也是Meteor的新手。
我正在为一个函数做一个Meteor.call(' getTheThing')。该函数正在获取一些信息并将信息作为响应返回。在我的浏览器中,我可以看到该方法返回正确的信息(字符串),但如何将该响应传入DOM?
(正如您所看到的,我尝试使用ReactDOM.findDOMNode(this.refs.result).html(response);
将其放入DOM中,但后来我在控制台中出现此错误:Exception in delivering result of invoking 'getTheThing': TypeError: Cannot read property 'result' of undefined
)
App = React.createClass({
findTheThing(event) {
event.preventDefault();
var username = ReactDOM.findDOMNode(this.refs.textInput).value.trim();
Meteor.call("getTheThing", username, function(error, response){
console.log(response);
ReactDOM.findDOMNode(this.refs.result).html(response);
});
ReactDOM.findDOMNode(this.refs.textInput).value = "";
},
render(){
return(
<div className="row">
<div className="col-xs-12">
<div className="landing-container">
<form className="username" onSubmit={this.findTheThing} >
<input
type="text"
ref="textInput"
placeholder="what's your username?"
/>
</form>
</div>
<div ref="result">
</div>
</div>
</div>
);
}
});
答案 0 :(得分:0)
this
位于不同的上下文中,因此不包含refs
。另外,您无法为html
设置Dom Element
。您需要更改为Jquery element
var _this = this;
Meteor.call("getTheThing", username, function(error, response){
console.log(response);
$(ReactDOM.findDOMNode(_this.refs.result)).html(response);
});
虽然我建议您将响应设置为状态并让组件重新呈现
完整的React方式
App = React.createClass({
getInitialState() {
return { result: "" };
},
shouldComponentUpdate (nextProps: any, nextState: any): boolean {
return (nextState['result'] !== this.state['result']);
},
findTheThing(event) {
event.preventDefault();
var username = ReactDOM.findDOMNode(this.refs.textInput).value.trim();
Meteor.call("getTheThing", username, function(error, response){
console.log(response);
_this.setState({ result: response });
});
ReactDOM.findDOMNode(this.refs.textInput).value = "";
},
render(){
return(
<div className="row">
<div className="col-xs-12">
<div className="landing-container">
<form className="username" onSubmit={this.findTheThing} >
<input
type="text"
ref="textInput"
placeholder="what's your username?"
/>
</form>
</div>
<div ref="result">{this.state['result']}</div>
</div>
</div>
</div>
);
}
});