javascript - 从另一个类调用函数(React)
问题描述
一般来说,我对 React 和 JS 很陌生,并且一直在学习各种教程。
HandleFormSubmit 运行后,我想刷新联系人管理表中显示的数据,因为我们刚刚推送了一堆新数据。
如何从 HandleFormSubmit 中调用 fetchData()?自从在 App 中呈现以来,我一直在苦苦挣扎。
谢谢
<script type="text/babel">
class ContactForm extends React.Component {
state = {
name: '',
emai: '',
country: '',
city: '',
job: '',
}
handleFormSubmit( event ) {
event.preventDefault();
let formData=new FormData();
formData.append('name', this.state.name)
formData.append('email', this.state.email)
formData.append('city', this.state.city)
formData.append('country', this.state.country)
formData.append('job', this.state.job)
axios({
method: 'post',
url: '/api/contacts.php',
data: formData,
config: { headers: {'Content-Type': 'multipat/form-data' }}
})
.then(function (response){
console.log(response)
this.fetchData();
})
.catch(function (response) {
console.log(response)
});
}
render() {
return (
<form>
<label>Name</label>
<input type="text" name="name" value={this.state.name} onChange={e => this.setState({ name: e.target.value})}/>
<label>Email</label>
<input type="email" name="email" value={this.state.email} onChange={e => this.setState({ email: e.target.value})}/>
<label>Country</label>
<input type="text" name="country" value={this.state.country} onChange={e => this.setState({ country: e.target.value})}/>
<label>City</label>
<input type="text" name="city" value={this.state.city} onChange={e => this.setState({ city: e.target.value})}/>
<label>Job</label>
<input type="text" name="job" value={this.state.job} onChange={e => this.setState({ job: e.target.value})}/>
<input type="submit" onClick={e => this.handleFormSubmit(e)} value="Create Contact" />
</form>)
}
}
class App extends React.Component {
state = {
contacts: []
}
render() {
return (
<React.Fragment>
<h1>Contact Management</h1>
<table border='1' width='100%'>
<tr>
<th>Name</th>
<th>Email</th>
<th>Country</th>
<th>City</th>
<th>Job</th>
</tr>
{this.state.contacts.map((contact) => (
<tr>
<td>{ contact.name }</td>
<td>{ contact.email }</td>
<td>{ contact.country }</td>
<td>{ contact.city }</td>
<td>{ contact.job }</td>
</tr>
))}
</table>
<ContactForm />
</React.Fragment>
);
}
fetchData() {
const url ='/api/contacts.php'
axios.get(url).then(response => response.data).then((data) => {
this.setState({ contacts: data })
console.log(this.state.contacts)
})
}
componentDidMount() {
this.fetchData();
}
}
ReactDOM.render(<App />, document.getElementById('root'));
</script>
解决方案
您可以将函数引用从父级传递给子级,如下所示
<ContactForm fetchData={this.fetchData}/>
在父组件中,您可以像这样调用该函数
this.props.fetchData()
PS:不要忘记在构造函数中绑定函数。
推荐阅读
- python - 找不到文件错误 Ray 安装 Windows
- visual-studio - 无法从另一类业务逻辑层访问公共类的 DataAccess 层
- java - 找到 sum = K 的子数组(连续)的数量(考虑时间复杂度)
- javascript - JavaScript 在单击时更改网格单元格的背景颜色
- kubernetes - 将子路径作为我在 k3s 上的后端服务的“根”路径?
- python - googletrans JSON解码错误
- bpmn - Camunda 使用任务变量返回不正确的任务列表
- javascript - 无法使用 XMLHttpRequest 将参数传递给 $_POST
- i18next - 如何使用 react-i18next
命名标签? - php - 更新到 WSL2 后无法从 PhpStorm 连接到 Xdebug