【发布时间】:2019-11-11 15:35:19
【问题描述】:
如果标题没有解释太多,我很抱歉。我有一个反应组件,它有一个按钮和一些文本,我用了 3 次。我希望每个按钮在单击时显示其文本,但隐藏其他文本。
我编写的代码使我能够在单击每个按钮时显示文本,但它不会隐藏其他按钮的文本。我可以制作 3 个组件,每个按钮一个,但我想尝试这种方法,我不确定我是否可以让另一个也起作用
反应组件:
import React from 'react'
export default class Button extends React.Component {
state={
display: 'none'
}
render() {
return (<div>
<button
onClick={()=>this.setState({display:'block'})}
style={{ width: "50px", height: "50px", display:"inline-block" }}>
{this.props.children}
</button>
<h1 style={{display: this.state.display}}>
{this.props.title}
</h1>
<img style={{display: this.state.display}} src={this.props.src} alt=""></img>
<p style={{display: this.state.display}}>
{this.props.descri}
</p>
</div>)
}
}
App.js:
import React from 'react';
import './App.css';
import Button from './sarra.js';
import Aa from './Aa.jpg';
import kacem from './b1.jpg';
import harold from './kacem.JPG';
/*
const person = [
{name:"sarah",
imgsrc:"" ,
description: "ipsum lorem "
},
{name:"sarah",
imgsrc:"" ,
description: "ipsum lorem "
},
{name:"sarah",
imgsrc:"" ,
description: "ipsum lorem "
}
]
*/
const isShown =() =>{
Button.style="backgroundColor: red"
}
function App() {
return (<div>
<Button title="Aa" descri="this is ali's profile" src={Aa} >ali</Button>
<Button title="harold" descri="this is harold's profile" src={harold} onClick={isShown()}>harold</Button>
<Button title="kacem" descri="this is kacem's profile" src={kacem} >kacem</Button>
</div>
);
}
export default App;
我也想过做一个函数来隐藏其他按钮,所以我做了一个简单的函数来简单的启动,就是isShown让按钮变成红色,但是没有成功。我不知道出了什么问题,所以如果我知道问题出在哪里,我可以更改它,以便使用它们的 ID 将其他按钮的显示更改为隐藏。
也许我也可以使用状态?在定义了 onclick 道具的组件中,是否可以编写另一行,使其他按钮的显示隐藏,另一个按钮
this.setState({display:'block'}
还在那儿?是否有与this 相悖的东西影响其他元素?
如果可能,您还可以向我展示如何在同一行中制作三个按钮。谢谢!
【问题讨论】:
标签: javascript reactjs