Html React JS this.setState在通过嵌套组件更新内容时不执行任何操作
我正在编写一个简单的react示例,该示例将根据用户在文本字段中输入的内容更改屏幕上标题的内容。以下是反应代码:Html React JS this.setState在通过嵌套组件更新内容时不执行任何操作,html,reactjs,Html,Reactjs,我正在编写一个简单的react示例,该示例将根据用户在文本字段中输入的内容更改屏幕上标题的内容。以下是反应代码: var GreeterForm = React.createClass({ onFormSubmit: function(e){ e.preventDefault(); var name = this.refs.name; this.refs.name.value = ''; this.props.onNew
var GreeterForm = React.createClass({
onFormSubmit: function(e){
e.preventDefault();
var name = this.refs.name;
this.refs.name.value = '';
this.props.onNewName(name);
},
render: function(){
return(
<form onSubmit={this.onFormSubmit}>
<input type="text" ref="name"/>
<button>Set Name</button>
</form>
);
}
});
var Greeter = React.createClass({
//returns an object of the default properties to be used
//these are used if no properties are passed in
getDefaultProps: function(){
return {
name: 'React!',
message: "this is from a component!"
};
},
//maintains a state for the component. Maintains the state as an object
//this is a default method for react and we override it.
getInitialState: function(){
return {
name: this.props.name
};
},
handleNewName: function(name){
this.setState({
name: name
});
},
//renders the greeter react component
render: function() {
var name = this.state.name;
var message = this.props.message;
return (
<div>
<h1>Hello {name}!</h1>
<p>{message}</p>
<GreeterForm onNewName={this.handleNewName}/>
</div>
);
}
});
var firstName = "DefaultName";
var mess = "This is a message from react."
//note that name and message are passed in as properties
ReactDOM.render(<Greeter name={firstName} message={mess}/>, document.getElementById('app'));
您没有发送输入值。您正在发送整个html元素 在
onFormSubmit
功能中更改此行
var name = this.refs.name;
到
您没有发送输入值。您正在发送整个html元素 在
onFormSubmit
功能中更改此行
var name = this.refs.name;
到
首先,检查在提交请求时是否调用了
handleNewName
form@KishoreBarik我在提交这个问题之前就这么做了,我在handleNewName
函数中的之前添加了一个警报
。设置状态
,它出现在屏幕上。第一次检查提交请求时是否调用了handleNewName
form@KishoreBarik我在提交这个问题之前就这么做了,我在handleNewName
功能中的this.setState
之前添加了一个警报
,它出现在屏幕上
var name = this.refs.name.value;