【问题标题】:Using useRef hook with React-Admin将 useRef 钩子与 React-Admin 一起使用
【发布时间】:2020-11-19 21:58:35
【问题描述】:

我尝试使用 useRef 挂钩创建对 React-Admin 元素的引用,但没有成功。

使用简单的 <input> 字段对本机 react.js 执行相同操作,但使用 react-admin 组件时引用为空。

有人知道如何在 react-admin 中引用元素吗?

const myForm = (props) => {

    const refContainer = useRef(null);

    const myClick = () => {
        console.log('clicked !', refContainer); // refContainer is null !!!
        refContainer.current.value = '1';
    };
    return <Edit {...props}>
        <SimpleForm>
        <TextInput source='myValue' ref={refContainer} value='0'/>
        <input type="button" value="change" onClick={myClick}/></SimpleForm>
    </Edit>;
};

【问题讨论】:

  • 为什么不通过 state 设置呢?创建一个保存该值的状态并在“myClick”中更改它。如果您只想更改文本,您可以尝试:“refContainer.current.setNativeProps({ text: '1' })”

标签: reactjs react-native react-hooks react-admin


【解决方案1】:

尝试改用 ref: inputRef https://material-ui.com/ru/api/input/

<TextField inputRef={refContainer} />

【讨论】:

  • 这是正确的。 React-admin 的 TextInput 将 inputRef 属性传递给 Material-UI 的 TextField。谢谢@MaxAlex。
猜你喜欢
  • 2019-06-22
  • 1970-01-01
  • 2021-02-15
  • 1970-01-01
  • 2022-01-08
  • 2020-03-07
  • 1970-01-01
  • 2020-09-01
  • 2020-04-22
相关资源
最近更新 更多