简体   繁体   English

在多个 div 中的 div 上显示或隐藏 React

[英]Show or Hide on div among multiple divs React

I was trying to render a component based on the dropdown click.我试图根据下拉单击呈现组件。

Here is my code这是我的代码

const App = () => {
    const [showPlayer, setShowPlayer] = useState();

    const switchVisibleDiv = ({divNumber}) => {
        setShowPlayer({showPlayer: divNumber})
    }

    return(
        <>
            <DropdownButton id="dropdown-basic-button" title="Dropdown Menu">
                {data.map((info, index) => (
                    <Dropdown.Item key={index} onClick={() => switchVisibleDiv(index)}>Title - {data.title}</Dropdown.Item>
                ))}
            </DropdownButton>

            {data.map((video, index) => (
            (showPlayer === index ?
                <Plyr
                key={index}
                options={options}
                source={{
                    type: 'video',
                    title: 'Example title',
                    sources: [
                        {
                        `${video.video_url}`,
                        type: 'video/mp4',
                        size: 1080,
                        }
                    ]
                    }}
                />
                : null)
            ))}
        </>
    )
}

But it does not seems to be working i took the reference from an answer from here which was a class component and tried converting that into function component.但它似乎不起作用我从这里的答案中获取参考,这是一个 class 组件,并尝试将其转换为 function 组件。

Link to answer 链接回答

You should change this callback function for the DropdownButton component.您应该为DropdownButton组件更改此callback function。

const switchVisibleDiv = ({divNumber}) => {
    setShowPlayer(divNumber)
}

It will be working then, the original approach is Class Component format and in Functional Component , we don't use like that, just pass the divNumber as a parameter for the setShowPlayer setter function.然后它将起作用,原始方法是Class Component格式,在Functional Component中,我们不会那样使用,只需将divNumber作为参数传递给setShowPlayer设置器 function。

Then it will work.然后它将起作用。

You need to set a number and not an object:您需要设置一个数字而不是 object:

    const switchVisibleDiv = (divNumber) => {
        setShowPlayer(divNumber})
    }

One more thing you could have done is remove the function and simply set state from here:您可以做的另一件事是删除 function 并从此处简单地设置 state :

<DropdownButton id="dropdown-basic-button" title="Dropdown Menu">
                {data.map((info, index) => (
                    <Dropdown.Item key={index} onClick={() => setShowPlayer(index)}>Title - {data.title}</Dropdown.Item>
                ))}
            </DropdownButton>

PS: Use something else instead of index as key . PS:使用其他东西而不是index作为key It is not recommended.不推荐。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM