【问题标题】:Is there a way to make a button function, that when pressed changes the title of another component in React?有没有办法制作一个按钮功能,当按下时会改变 React 中另一个组件的标题?
【发布时间】:2021-08-23 08:47:52
【问题描述】:

我正在尝试制作一个音乐应用程序,首页上有按钮。当您按下其中一个按钮时,会弹出一张卡片。我希望卡片标题取决于按下了哪个按钮。我正在为我的项目使用反应。有没有办法做到这一点?

我的按钮有这个功能

export function GenreButton({ text }) {
    return <StyledGenreButton>{text}</StyledGenreButton>


export function Button (){


return (
    <>
        <Wrapper>
            <GenreButton text='Country' />
            <GenreButton text='Disco' />
            <GenreButton text='Funk' /> 
            <GenreButton text='House' /> 
       
        </Wrapper>
    </>
)

}

对于我的卡片组件:

const CardTitle2 = () => {
    const [cardTitle, setCardTitle] = useState ('string')
    return <StyledCardTitle onClick={() => setCardTitle('New Title')}>{cardTitle}</StyledCardTitle> 

到目前为止,我已经尝试将 Card 组件导入到我的 Button 组件中,并在我的 GenreButton 函数中添加了一个 onClick 属性。

export function GenreButton({ text, onClick }) {
    return <StyledGenreButton>{[text, onClick]}</StyledGenreButton>

然后在 return 语句中将 onClick 插入到其中一个 GenreButtons 上。

现在我知道,当我按下标题时,我的卡片标题将从“字符串”更改为“新标题”。但是我可以将卡片的标题更改为与按钮输入的字符串相同吗?

【问题讨论】:

标签: javascript reactjs web-deployment


【解决方案1】:

所以我想出了怎么做。

export function Button (){ 
const [title, setTitle] = useState('')
function GenreButton({ text }) {
    return <StyledGenreButton onClick={() => setTitle(text)}>{text}</StyledGenreButton>
}


<Wrapper>
            <GenreButton text='Country'/>
            <GenreButton text='Disco' />
            <GenreButton text='Electro' /> 
</Wrapper>
            <CardWrapper>
                <CardTitle title={title} />
            </CardWrapper>

【讨论】:

    【解决方案2】:

    你应该提升状态,例如提升状态到你的主页:

    const HomePage = () => {
       const [title, setTitle] = useState('string')
    
       return (
         <Card title={title}/>
         <Buttons setTitle={setTitle}/>
       )
    }
    

    供参考:https://reactjs.org/docs/components-and-props.html

    【讨论】:

    • 嗯...这似乎无法解决我的问题。也许我做错了什么......
    猜你喜欢
    • 1970-01-01
    • 2020-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多