首页 > 解决方案 > 调用钩子函数以显示传入参数的钩子实例

问题描述

假设我有一个带有 ref containerRef 的 Container 钩子。

我希望能够使用传入参数的钩子实例调用 show 方法,以便在 MyContainer 中呈现钩子实例,如下所示:

<div>
    <MyContainer ref={containerRef}/>
    <button onClick={()=>containerRef.current.show(myHookInstance)}>click</button>
</div>

这是我的完整代码:

import React, {forwardRef, useImperativeHandle, useState} from 'react';

const MyContainer = forwardRef((props, ref) => {
    const [showContent, setShowContent] = useState('');

    useImperativeHandle(ref, () => ({
        show: (content = null) => {
            setShowContent(content)
        },
    }));
    return (
        <div>
            this is the content:
            {showContent}
        </div>
    )
})

const MyForm = () => {
    const [name, setName] = useState("");
    return (
        <form>
            <input type="text"
                   id="name"
                   value={name}
                   onChange={(e) => setName(e.target.value)}
            />
        </form>
    )
}

const App = () => {
    const containerRef = React.createRef()
    const myForm = MyForm()
    return (
        <div>
            <MyContainer ref={containerRef}/>
            <button onClick={()=>containerRef.current.show(myForm)}>click</button>
        </div>
    );
}

export default App;

问题是当我输入表单输入时,它没有显示出来。

据我了解,将钩子实例存储在状态中是一种非常糟糕的做法。

你有什么建议吗?

非常感谢您的帮助

标签: reactjs

解决方案


谢谢 Shubham,但实际上我需要 show 方法来接收任何内容作为参数,如下面的代码:

import React, {forwardRef, useImperativeHandle, useState} from 'react';

const MyContainer = forwardRef((props, ref) => {
    const [showContent, setShowContent] = useState('');

    useImperativeHandle(ref, () => ({
        show: (content = null) => {
            setShowContent(content)
        },
    }));
    return (
        <div>
            this is the content:
            {showContent}
        </div>
    )
})

const MyForm = () => {
    const [name, setName] = useState("");
    return (
        <form>
            <input type="text"
                   id="name"
                   value={name}
                   onChange={(e) => setName(e.target.value)}
            />
        </form>
    )
}

const AnotherContent = () => {
    return (
        <div>
            Another content !
        </div>
    )
}

const App = () => {
    const containerRef = React.createRef()
    const myForm = <MyForm />
    const anotherContent = <AnotherContent />
    return (
        <div>
            <MyContainer ref={containerRef}/>
            <button onClick={()=>containerRef.current.show(myForm)}>show MyForm</button>
            <button onClick={()=>containerRef.current.show(anotherContent)}>show AnotherContent</button>
        </div>
    );
}

export default App;

你会如何改进它?


推荐阅读