reactjs如何获取一个组件(子组件)的值到另一个组件(父组件)?
How to get the value from one component(Child Component) to another component (Parent Component) in reactjs?
我正在从事 Reactjs Weather 项目。提交后我在子组件 (Form.js) 中的一个方法中获取值,我需要在父组件 (App.js) 中获取该值。如何获得该值?
- App.js 文件(父组件)
getWeather = async (e) => {
e.preventDefault();
}
- Form.js 文件(子组件)
import React, { Component } from 'react'
import Background from '../video/rain_drop2.jpg';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { MDBContainer,
MDBRow,
MDBCol,
MDBCard,
MDBCardBody,
MDBCardHeader,
MDBBtn,
MDBInput } from 'mdbreact'
const sectionStyle = {
backgroundImage: `url(${Background})`,
opacity: '0.92',
width: '90%',
backgroundSize: 'cover',
backgroundPosition: 'center',
height:'99%',
position:'absolute',
filter:'blur(1.8px)'
};
class Form extends React.Component {
constructor(props){
super(props);
this.state = {
fields: {},
errors: {}
}
}
handleValidation(){
let fields = this.state.fields;
let errors = {};
let formIsValid = true;
//Name
if(!fields["city"]){
formIsValid = false;
errors["city"] = "Cannot be empty";
}
this.setState({errors: errors});
return formIsValid;
}
submitDetails = (e) => {
e.preventDefault();
// I want this value to be accessed in App.js file
const city = e.target.city.value
console.log('VALUE', city)
browserHistory.push()
if(this.handleValidation()){
toast("Form Submitted!.")
}else{
toast("Form has errors.")
}
}
handleChange(field, e){
let fields = this.state.fields;
fields[field] = e.target.value;
this.setState({fields});
}
render(){
return (
<div>
<MDBContainer>
<MDBRow>
<MDBCol>
<MDBCard style={sectionStyle}></MDBCard>
<MDBCard className="card" style={{zIndex:'1', background: 'none'}}>
<MDBCardBody >
<MDBCardHeader style={{background: '#ecf0f1', opacity:'0.7', borderRadius: '10px',
fontFamily: 'Josefin Sans'}}>
<h3 className="my-3 text-center" style={{color: '#535c68'}}>
Weather Finder
</h3>
</MDBCardHeader>
<br/>
<form onSubmit= {this.submitDetails.bind(this)}>
<div className="blue-grey-text">
<span className="error">{this.state.errors["name"]}</span>
<MDBInput
ref="city"
label="City"
icon="city"
type="text"
name="city"
id="text-input"
onChange={this.handleChange.bind(this, "city")}
value={this.state.fields["city"]}
/>
<span style={{color: "red"}}>{this.state.errors["city"]}</span>
</div>
<br/>
<div className="text-center mt-4">
<MDBBtn
color="blue-grey"
className="mb-3"
type="submit"
value="Submit"
>
Search Weather
</MDBBtn>
<ToastContainer />
</div>
</form>
</MDBCardBody>
</MDBCard>
</MDBCol>
</MDBRow>
</MDBContainer>
</div>
)
}
}
export default Form;
非常感谢任何建议...提前致谢
在父组件中渲染子组件时,将父组件中定义的函数作为prop传递给子组件。
当您在子组件中获得所需的值时,调用从父组件传递的函数作为 prop 并将该值作为参数传递给该函数。
父组件
// function to be called from child component
foo = (value) => {
// code
};
render() {
return (
<ChildComponent foo={this.foo}/>
);
}
子组件
bar = () => {
const value = // get the value
// call the foo function of parent component and pass the value
this.props.foo(value);
};
最常用的方法是使用回调:
- 在您定义新属性的子表单组件中 'onSubmit'
- 在父 App 组件中,您使用 'data' 参数定义 'submitHandler' 函数:
handleSubmit = data => {/* your logic here */}
render => (<Form onSubmit={this.submitHandler}/>)
- 子组件方法的最后一步 'submitDetails' 你调用
this.props.onSubmit(data);
您可以为此提供来自父组件的回调:
const Parent = () => {
const [ weather, setWeather ] = useState(null);
return (
<Child setWeather={ setWeather } />
);
};
const Child = ({ setWeather }) => {
const getWeather = () => { ... };
const onClick = () => {
const weather = getWeather();
setWeather(weather);
};
return (
<button onClick={ onClick }>Get Weather</button>
);
}
我正在从事 Reactjs Weather 项目。提交后我在子组件 (Form.js) 中的一个方法中获取值,我需要在父组件 (App.js) 中获取该值。如何获得该值?
- App.js 文件(父组件)
getWeather = async (e) => {
e.preventDefault();
}
- Form.js 文件(子组件)
import React, { Component } from 'react'
import Background from '../video/rain_drop2.jpg';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { MDBContainer,
MDBRow,
MDBCol,
MDBCard,
MDBCardBody,
MDBCardHeader,
MDBBtn,
MDBInput } from 'mdbreact'
const sectionStyle = {
backgroundImage: `url(${Background})`,
opacity: '0.92',
width: '90%',
backgroundSize: 'cover',
backgroundPosition: 'center',
height:'99%',
position:'absolute',
filter:'blur(1.8px)'
};
class Form extends React.Component {
constructor(props){
super(props);
this.state = {
fields: {},
errors: {}
}
}
handleValidation(){
let fields = this.state.fields;
let errors = {};
let formIsValid = true;
//Name
if(!fields["city"]){
formIsValid = false;
errors["city"] = "Cannot be empty";
}
this.setState({errors: errors});
return formIsValid;
}
submitDetails = (e) => {
e.preventDefault();
// I want this value to be accessed in App.js file
const city = e.target.city.value
console.log('VALUE', city)
browserHistory.push()
if(this.handleValidation()){
toast("Form Submitted!.")
}else{
toast("Form has errors.")
}
}
handleChange(field, e){
let fields = this.state.fields;
fields[field] = e.target.value;
this.setState({fields});
}
render(){
return (
<div>
<MDBContainer>
<MDBRow>
<MDBCol>
<MDBCard style={sectionStyle}></MDBCard>
<MDBCard className="card" style={{zIndex:'1', background: 'none'}}>
<MDBCardBody >
<MDBCardHeader style={{background: '#ecf0f1', opacity:'0.7', borderRadius: '10px',
fontFamily: 'Josefin Sans'}}>
<h3 className="my-3 text-center" style={{color: '#535c68'}}>
Weather Finder
</h3>
</MDBCardHeader>
<br/>
<form onSubmit= {this.submitDetails.bind(this)}>
<div className="blue-grey-text">
<span className="error">{this.state.errors["name"]}</span>
<MDBInput
ref="city"
label="City"
icon="city"
type="text"
name="city"
id="text-input"
onChange={this.handleChange.bind(this, "city")}
value={this.state.fields["city"]}
/>
<span style={{color: "red"}}>{this.state.errors["city"]}</span>
</div>
<br/>
<div className="text-center mt-4">
<MDBBtn
color="blue-grey"
className="mb-3"
type="submit"
value="Submit"
>
Search Weather
</MDBBtn>
<ToastContainer />
</div>
</form>
</MDBCardBody>
</MDBCard>
</MDBCol>
</MDBRow>
</MDBContainer>
</div>
)
}
}
export default Form;
非常感谢任何建议...提前致谢
在父组件中渲染子组件时,将父组件中定义的函数作为prop传递给子组件。
当您在子组件中获得所需的值时,调用从父组件传递的函数作为 prop 并将该值作为参数传递给该函数。
父组件
// function to be called from child component
foo = (value) => {
// code
};
render() {
return (
<ChildComponent foo={this.foo}/>
);
}
子组件
bar = () => {
const value = // get the value
// call the foo function of parent component and pass the value
this.props.foo(value);
};
最常用的方法是使用回调:
- 在您定义新属性的子表单组件中 'onSubmit'
- 在父 App 组件中,您使用 'data' 参数定义 'submitHandler' 函数:
handleSubmit = data => {/* your logic here */}
render => (<Form onSubmit={this.submitHandler}/>)
- 子组件方法的最后一步 'submitDetails' 你调用
this.props.onSubmit(data);
您可以为此提供来自父组件的回调:
const Parent = () => {
const [ weather, setWeather ] = useState(null);
return (
<Child setWeather={ setWeather } />
);
};
const Child = ({ setWeather }) => {
const getWeather = () => { ... };
const onClick = () => {
const weather = getWeather();
setWeather(weather);
};
return (
<button onClick={ onClick }>Get Weather</button>
);
}