如何从react中的子组件获取Value



我创建了一个InputComponent,我想在其他组件中导入这个组件并提交,但我做不到。我如何从FormComponent 中的子组件中获取值

InputComponent.js

import React, {Component} from 'react';
class InputComponent extends Component {
constructor(props) {
super(props);
this.state = { currentVal: null }
}
render() { 
return ( 
<div>
<input  
value={this.state.currentVal}
onChange={(event) => this.setState({currentVal:event.target.value })}
/> 
</div>
);
}
}
export default InputComponent;

FormComponent.js

import React,{Component} from 'react';
import InputComponent from '../../components/common/InputComponent';
class FormComponent extends Component {
constructor(props) {
super(props);
this.state = {  }
}

CallSubmit= (event) => {  
// how can get username and password ?
event.preventDefault();
console.log(event.target.vale)
}
render() { 
return ( 
<div style={{width:100, height:500, marginTop:100}}>
<form onSubmit={  this.CallSubmit }>
<InputComponent name="username" />
<InputComponent name="password" />
<button>Send it</button>
</form>
</div>
);
}
}
export default FormComponent;

您可以在子组件上创建onChange操作,例如这里是您的FormComponent:创建此函数以处理更改:

onChangeUsername(username){
this.setState({username})
}

将道具传递给子组件:

<InputComponent name="username" onChange = {this.onChangeUsername} />

在子组件(InputComponent(中,您可以访问这些道具并将数据传递给它:

this.props.onChange(event.target.value)

在父组件中移动onChange函数,并将用户名和密码存储在FormComponent组件中

在React中,数据以一种方式从父级流到子级。

因此,您需要在FormComponent处获得输入的实际状态,并将它们作为道具传递给InputComponent,以及在FormComponent处处理它的函数。

<div>
<InputComponent 
input={this.state.username} 
onChange={this.handleInputChange}
/>
<InputComponent 
input={this.state.password} 
onChange={this.handleInputChange}
/>
</div>

一篇理解它的好文章:https://openclassrooms.com/en/courses/4286486-build-web-apps-with-reactjs/4286721-understand-one-way-data-bindings

最新更新