例如,如果我有一个功能组件 Dropdown 从一个 api 接收数据来填充一个下拉选择,并使用以下钩子来更新所选值的状态
const [value, setValue] = React.useState();
然后我如何访问/读取 Dropdown 组件之外的值(在本例中为数字数组)?
为了更好的上下文,我将首先包括使用 Dropdown 组件的位置:
import React from 'react';
import Dropdown from '../Components/Dropdown.js'
import GraphTypeDropdown from '../Components/GraphTypeDropdown.js'
function CreateGraph() {
//function receiving and returning data (array of data points and their heading) from api
async function getData() {
const response = await fetch('/dropdowndata');
const receivedData = await response.json();
return receivedData;
}
//assigning data to myData variable
const myData = getData();
//myData is passed to Dropdown components as a prop to allow selection of data columns
//GraphTypeDropdown allows selection of the graph "type"
return (
<div>
<Dropdown myData={myData} />
<Dropdown myData={myData} />
<Dropdown myData={myData} />
<Dropdown myData={myData} />
<Dropdown myData={myData} />
<GraphTypeDropdown />
</div>
)
}
export default CreateGraph;
还有下拉功能组件的完整代码
import React from 'react';
import './Dropdown.css';
function Dropdown(props) {
const [columns, setColumns] = React.useState([]);
const [value, setValue] = React.useState();
//maps the prop myData to be the label and value of the dropdown list
React.useEffect(() => {
async function getColumns() {
props.myData.then(function(result) {
setColumns(result.map(({ heading, values }) => ({ label: heading, value: values })));
});
}
getColumns();
}, [props.myData]);
//creates a dropdown where value (array of data points) can be selected with label (column headings)
//value selected is then saved in the state of the dropdown
return (
<select className='DropDown'
value={value}
onChange={(e) => setValue(e.currentTarget.value)}
>
{columns.map(({ label, heading, value }) => (
<option className='DropDown'
key={heading}
value={value}
>
{label}
</option>
))}
</select>
);
}
export default Dropdown;
我将如何使用/访问在五个 Dropdown 组件中分配给 value 的数组?
答案 0 :(得分:0)
您的问题“访问组件外部的值?”的答案是:
您通常无法从组件外部访问功能组件的状态。
你可以做的是:
现在,最佳解决方案在很大程度上取决于您的用例。
传递“向上”状态的示例是:
function Dropdown(props) {
// ...
React.useEffect(() => {
props.onLoaded( columns );
}, [ columns ]);
// ...
}
function CreateGraph() {
// ...
<Dropdown
myData={ myData }
onLoaded={
(columns) => {
console.log('columns:', columns);
}
}
/>
// ...
}