我有一个从下拉列表中选择国家的函数。我把它单独放在一个文件里了。然后在我的dashboard。js中,我只是调用函数来显示。但是我如何从Dashboard.js中获得值呢?
CountrySelector.js
import React, { useState, useMemo } from 'react'
import Select from 'react-select'
import countryList from 'react-select-country-list'
function CountrySelector() {
const [value, setValue] = useState("")
const options = useMemo(() => countryList().getData(), [])
const changeHandler = value => {
setValue(value)
}
const style = {
display: "inline-block",
width: "300px"
};
return <div style={style}><Select options={options} value={value} onChange={changeHandler} /></div>
}
export default CountrySelector;
Dashboard.js
import CountrySelector from '../util/CountrySelector';
const Dashboard = () => {
return(
<div>
<CountrySelector/>
</div>
);
};
export default Dashboard;
我知道props不起作用,因为你把数据从父级传递给子级。我想把数据从子元素传递给父元素。如有任何帮助,不胜感激。
把你的状态放到父组件中,并把它们作为道具传递给子组件
import { useState, useMemo } from 'react';
import CountrySelector from '../util/CountrySelector';
import countryList from 'react-select-country-list';
const Dashboard = () => {
const [value, setValue] = useState('');
const options = useMemo(() => countryList().getData(), []);
return (
<div>
<CountrySelector value={value} setValue={setValue} options={options} />
</div>
);
};
export default Dashboard;
import Select from 'react-select';
function CountrySelector({ value, setValue, options }) {
const style = {
display: 'inline-block',
width: '300px',
};
return (
<div style={style}>
<Select options={options} value={value} onChange={setValue} />
</div>
);
}
export default CountrySelector;