gpt4 book ai didi

javascript - React 在表单提交上获取输入值并显示它

转载 作者:行者123 更新时间:2023-12-03 05:20:19 29 4
gpt4 key购买 nike

我有以下脚本:http://codepen.io/AlexanderWeb00/pen/gLVbjL?editors=0010

class Wrapper extends React.Component {
constructor(props) {
super(props);
this.state = {
name: ''
};
}
handleFirstName(e) {
this.setState({name: e.target.value});
}
render(){
return (
<section>
<h2>welcome</h2>
<TShirt name={this.state.name} />
<FormButton action={this.handleFirstName.bind(this)} />
</section>
)
}
};

class TShirt extends React.Component {
render(){
return (
<section>
<div>
<p>Name: {this.props.name}</p>
</div>
</section>
)
}
};
class Extention extends React.Component {
render(){
return (
<section>
<div>
<p>badaboom</p>
</div>
</section>
)
}
};
var FormButton = React.createClass({
getInitialState: function() {
return {'submitted': false};
},

handleSubmit: function(e) {
e.preventDefault();
this.setState({'submitted': true });
},
render: function() {
if (this.state.submitted) {
return <Extention/>;
}
else {
return (
<form role="form" onSubmit={this.handleSubmit}>
<input type="text" />
<input type="submit" value="submit" />
</form>
);
}
}
});

ReactDOM.render(<Wrapper />, document.getElementById('app'));

我想显示从输入收集的值

<input type="text" />

这里:

<p>Name: {this.props.name}</p>, inside the TShirt component.

目前仅在提交表单后显示新组件。当我构建应用程序时,T 恤组件将更新更多内容。

最佳答案

您可以使用refs获取 T 恤输入字段的值,然后调用传递给 action 属性中的 FormButton 组件的回调函数。

var FormButton = React.createClass({ 
getInitialState: function() {
return {'submitted': false};
},

handleSubmit: function(e) {
e.preventDefault();
var tshirt = this.refs.tshirt.value;
this.setState({submitted: true }, function() {
this.props.action(tshirt);
});
},
render: function() {
if (this.state.submitted) {
return <Extention/>;
}
else {
return (
<form role="form" onSubmit={this.handleSubmit}>
<input type="text" ref="tshirt" />
<input type="submit" value="submit" />
</form>
);
}
}
});

然后将 handleFirstName 方法修改为:

handleFirstName(tshirt) {
this.setState({name: tshirt});
}

关于javascript - React 在表单提交上获取输入值并显示它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41415262/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com