![](/img/trans.png)
[英]In React, how can a parent component set state from the response an async fetch function performed in a child component?
[英]How to set a particular state of a parent component from child component in React?
我是 React 的新手。 我正在嘗試對表單元素進行簡單驗證。 我堅持驗證輸入數據並將 'name_error' state 設置為<p>
標記內的錯誤消息。 在下面留下我的代碼
// App.js
import React, { Component } from 'react';
import ValidateName from './component/validation';
import Modal from './modal';
class Home extends Component {
state = {
show: false,
name: "",
name_error: ""
}
handleChanges = (e) => {
const name = e.target.name;
const value = e.target.value;
this.setState({[name] : value})
}
render() {
console.log(this)
return (
<div>
<div className='Main'>
{/* < Main /> */}
<button id='add' onClick={()=>{this.setState({show: true})}}>Add</button>
</div>
{this.state.show &&
<Modal>
<form>
<div className='modalContainer'>
<b className='title'>Register</b>
<button id='xmark' onClick={()=>{this.setState({show: false})}} >×</button>
<label for='name' >Name</label><br />
<input type="text" id='name' placeholder='Enter your name here' name="name" onChange={this.handleChanges}/><br />
< ValidateName content={this.state.name} />
<button type='submit'>Sign Up</button>
<button>Cancel</button>
</div>
</form>
</Modal>}
</div>
);
}
}
export default Home;
// Modal.js
import React, { Component } from 'react';
class Modal extends Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
export default Modal;
//validation.js
class ValidateName extends Component {
err1 ='Please enter any name';
err2 = 'Use only letters in this field';
render() {
const ren = this.props.content.length === 0 ? (<p>{this.err1}</p> ) :
(this.props.content.match(/[a-zA-Z]+$/) ? '' : <p>{this.err2}</p>)
return ren;
}
}
請提出一個想法,當用戶輸入錯誤時,將name_error
設置為“請輸入任何名稱”或“在此字段中僅使用字母”
State應該是這樣的,
constructor(props){
super(props);
this.state = {
show: false,
name: "",
name_error: ""
}
}
並且還使用回調更新 state。 這會有所幫助,
this.setState({[name] : value},() =>{console.log(this.state)})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.