例如,如果我有一个功能组件 Dropdown,它从 api 接收数据来填充下拉选项,并使用以下钩子(Hook)来更新所选值的状态
const [value, setValue] = React.useState();
然后我如何访问/读取下拉组件外部的值(在本例中为数字数组)?
为了更好的上下文,我将首先包括使用下拉组件的位置:
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;
我如何能够使用/访问分配给五个下拉组件中的值的数组?
最佳答案
您的问题“访问组件外部的值?”的答案是:
您通常无法从功能组件外部访问该组件的状态。
你能做的是:
- 将 Prop “向下”传递给 child
- props 可以是回调函数,这样你就可以传递状态“up”
- 使用具有全局状态的框架,例如 redux .
现在,最佳解决方案是什么在很大程度上取决于您的用例。
“向上”传递状态的示例是:
function Dropdown(props) {
// ...
React.useEffect(() => {
props.onLoaded( columns );
}, [ columns ]);
// ...
}
function CreateGraph() {
// ...
<Dropdown
myData={ myData }
onLoaded={
(columns) => {
console.log('columns:', columns);
}
}
/>
// ...
}
关于javascript - 如何访问组件外部的功能组件状态? - react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65669542/