0
我一直在玩reactjs,並且構建一些基本的表單都很好,但是當我試圖打入更小的組件時,它變得複雜了 我有一個簡單的組件其中稱爲XMLParser,它內部有兩個較小的組件,分別稱爲XMLInput和XMLResult。如何將onChange傳遞給無狀態組件
XMLResult非常簡單,它只是將值作爲道具傳遞,但無法弄清楚什麼是最好的使用XMLInput的方案,我無法讓綁定與子組件一起工作,感謝任何指針。
function EppResult(props) {
const resultXML = props.xmlData;
return <div style={styles.child}>
<textarea style={styles.outputBox} name="resultXML" value={resultXML} readOnly/>
</div>;
}
class EppInput extends Component{
render(){
return <textarea
style={styles.inputBox}
placeholder="Enter XML here!"
name="xmlData"
value={this.props.value}
onChange={this.props.handleInputChange}
/>;
}
}
class XMLParser extends Component {
constructor(props) {
super(props);
this.state = {xmlData : ""};
this.state = {resultXML : ""};
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
console.log("do submit");
}
handleInputChange(event) {
const target = event.target;
const value = target.type === "checkbox" ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
render() {
return (
<div style={styles.container}>
<form onSubmit={this.handleSubmit}>
<div style={styles.container}>
<div style={styles.child}>
<XMLInput value={this.state.xmlData} onChange={this.handleInputChange} />
</div>
<div style={styles.child}>
<div style={styles.formContainer}>
<button style={styles.formElement}>Run!</button>
</div>
</div>
<XMLResult xmlData={this.state.resultXML}/>
</div>
</form>
</div>
);
}
}
爲什麼你有你自己的處理程序處理輸入,如果組件沒有內部狀態? – Li357
什麼是更好的方法?基本上我想要一個笨拙的輸入元素,讓我說我以後會對此輸入進行驗證,我不希望解析器組件變得太大,所以我創建了它自己的組件。不確定它是做這件事的好方法。 @AndrewLi – add9