【问题标题】:on button return id to show specific json react js在按钮上返回 id 以显示特定的 json 反应 js
【发布时间】:2019-07-20 20:30:53
【问题描述】:
【问题讨论】:
标签:
javascript
json
reactjs
web-applications
jsx
【解决方案1】:
对此的简单解决方案是扩展CZButton 组件,使其接受person 属性,然后可以在弹出对话框中呈现person 数据:
/* Adapted from your codesandbox sample */
class CZButton extends React.Component {
constructor(props) {
super(props);
this.state = { open: false };
}
toggle = () => {
let { toggle } = this.state;
this.setState({ open: !this.state.open });
};
render() {
const { open } = this.state;
return (
<div>
{" "}
<button onClick={this.toggle}>Show</button>
<Drawer
open={this.state.open}
onRequestClose={this.toggle}
onDrag={() => {}}
onOpen={() => {}}
allowClose={true}
modalElementClass="modal"
containerElementClass="my-shade"
parentElement={document.body}
direction="bottom" >
{/* This render the contents of the `person` prop's `email` field in dialog */}
<div>{this.props.person.email}</div>
{/* This renders the contents of `person` prop in dialog */}
<div>{JSON.stringify(this.props.person)}</div>
</Drawer>
</div>
);
}
}
看到您的 CZButton 现在正在渲染 person 属性的内容,上面的更改还要求您在渲染 CZButton 时在 PersonList 组件的 render() 方法中提供此数据,如下所示:
<div className="row">
{console.log(items)}
{items.map(item => (
<Person
className="person"
Key={item.id.name + item.name.first}
imgSrc={item.picture.large}
Title={item.name.title}
FName={item.name.first} >
{/* Pass the "person item" into our new person prop when rendering each CZButton */ }
<CZButton person={item} />
</Person>
))}
</div>
Here is a forked copy of your original code 上面提到的更新供您试用。希望这会有所帮助!
【解决方案2】:
在您的PersonList 组件中,当您map 您的每个项目时,您希望将项目的email 作为道具发送到CZButton,如下所示:
{items.map(item => (
<Person
className="person"
Key={item.id.name + item.name.first}
imgSrc={item.picture.large}
Title={item.name.title}
FName={item.name.first}
>
{" "}
<CZButton email={item.email} />
</Person>
))}
现在,每个CZButton 都有一个名为email 的道具。在你的CZButton 的render 方法中,你会希望Drawer 的内容看起来像这样:
<Drawer ...>
<div>{this.props.email || "No email address for this person."}</div>
</Drawer>
您可以尝试一下,看看它是否适合您。