【发布时间】:2019-12-31 19:23:24
【问题描述】:
我正在切换到使用 Hooks 构建组件,我正在努力使用 useRef() 设置参考
父级(引用目前仅添加到一个组件,因为我想确保在将功能扩展到其他组件之前它可以正常工作):
export default function UserPanels({ selected_client } ) {
const classes = useStyles();
const [value, setValue] = useState(0);
const container = useRef( null );
function handleChange(event, newValue) {
setValue(newValue);
container.current.displayData();
}
return (
<div className={classes.root}>
<UserTabs
value={value}
onChange={handleChange}
indicatorColor="primary"
textColor="primary"
variant="fullWidth"
aria-label="full width tabs example"
>
<Tab label='Service User' {...a11yProps(0)} />
<Tab label='Care Plan' {...a11yProps(1)} />
<Tab label='Contacts' {...a11yProps(2)} />
<Tab label='Property' {...a11yProps(3)} />
<Tab label='Schedule' {...a11yProps(4)} />
<Tab label='Account' {...a11yProps(5)} />
<Tab label='Invoices' {...a11yProps(6)} />
<Tab label='Notes' {...a11yProps(7)} />
<Tab label='eMAR' {...a11yProps(8)} />
</UserTabs>
<TabPanel value={value} index={0}>
<UserDetailsContainer
selected_client={ selected_client }
/>
</TabPanel>
<TabPanel value={value} index={1}>
Care Plan
</TabPanel>
<TabPanel value={value} index={2}>
<ContactsContainer
ref={ container }
selected_client={ selected_client }
/>
</TabPanel>
<TabPanel value={value} index={3}>
Property
</TabPanel>
<TabPanel value={value} index={4}>
Schedule
</TabPanel>
<TabPanel value={value} index={5}>
Account
</TabPanel>
<TabPanel value={value} index={6}>
Invoices
</TabPanel>
<TabPanel value={value} index={7}>
Notes
</TabPanel>
<TabPanel value={value} index={8}>
eMAR
</TabPanel>
</div>
);
}
孩子:
export default function ContactsContainer( props ) {
const [ state, setState ] = useState({
contact_records: contacts,
data_ready: true
});
function displayData() {
console.log( 'display time' );
}
if ( !state.data_ready ) return null
return (
<>
{
state.contact_records.map( ( contact ) => {
return <ContactRecord contact={ contact } />
} )
}
</>
)
}
基本上,我正在尝试从父函数调用子函数,但 ref.current 的计算结果为 null,当调用 handleChange() 时,我收到错误 container.current is null 并且我经常看到错误 Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
请注意,我已经测试过forwardRef:
<ContactsContainer
ref={ container }
selected_client={ selected_client }
/>
而且,虽然这消除了错误,但它并没有解决问题。我从来没有遇到过将 refs 与类组件一起使用的问题,但我似乎在这里遗漏了一些东西。
【问题讨论】:
标签: javascript reactjs react-hooks