我正在探索 React.js,我正在尝试做一些相当简单的事情。当用户成功提交他们的电子邮件时,我想更新我的网络应用程序特定部分的文本。
我目前拥有的:
var SignupForm = React.createClass({
getInitialState: function() {
return {email: ''};
},
render: function() {
var email = this.state.value;
return (
<div>
<input type="email" className="input_field" ref="email" value={email} />
<a href="#" className="button" onClick={this.saveAndContinue}>Request Invite</a>
</div>
)
},
saveAndContinue: function(e) {
e.preventDefault()
// Get values via this.refs
email = this.refs.email.getDOMNode().value
request = $.ajax({
url: "/store",
type: "post", success:function(data){
this.setState({email: data})
},
data: {'email': email} ,beforeSend: function(data){console.log(data);}
});
}
});
React.render(<SignupForm/>, document.getElementById('content'));
我要更新的文本位于 html 元素中,如下所示:
<h1 class="home-two-question">This is the text!</h1>
我想将其更新为:
<h1 class="home-two-question">You entered the text!</h1>
邮件提交成功后。知道如何做到这一点吗?
最佳答案
我建议将所有元素放在 React 组件中。
您可以将其放置在另一个组件中并在组件之间建立通信或放置在一个组件中。
下面是h1在同一个组件中的情况。
像这样添加一个ref属性
<h1 class="..." ref="myh1"></h1>
在 componentDidMount 中,h1 引用可以像这样存储(语法 根据 react 版本不同)
componentDidMount: function () {
this.myh1 = React.findDOMNode(this.refs.myh1);
}
现在您有了引用,您可以像这样从任何地方更新它
$(this.myh1).html(...);
关于javascript - 使用 react.js 单击按钮后更新文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31150751/