是否有一种方法使按钮功能,当按下时改变React中另一个组件的标题?



我想做一个音乐应用程序,在首页有按钮。当你按下其中一个按钮时,就会弹出一张卡片。我希望卡片的标题取决于哪个按钮被按下。我在我的项目中使用react。这有可能吗?

我的按钮有这个函数

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>
</>
)

}

对于我的card组件:

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>

然后在返回语句中的一个genrebutton上插入一个onClick。

现在我知道,我的卡标题将从'string'改为'New title ',当我按下标题。但是否有可能,我可以改变我的卡的标题等于我的字符串输入从按钮?

于是我想出了办法。

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>

你应该将state提升,例如将state提升到你的主页:

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

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