如何在单击按钮时显示子项详细信息


App.js-
class App extends Component{
render(){
const data= [
{
id: 1,
name: "John Smith",
email: "jsmith@test.com",
phone: "123456789",
details:"john smith details"

}, 
{
id: 2,
name: "ABCD",
email: "abcd@test.com",
phone: "987654321"
},
{
id: 3,
name: "Tyrion",
email: "tyrion@test.com",
phone: "123412345"
},
];
return(
<div >
<Customers item={data}  />
</div>

)
}
}
export default App;
Customer.js-
class Customers extends Component{
constructor(props) {
super(props);
this.state = {};
}
handleclick= (datalist) => {
this.setState({
})
}
render(){
const item = this.props.item
//uses map method 
const newarray=item.map( (cval)=>{
return(
<div>
<h1>{cval.name}</h1> 
<p>{cval.email}</p>
{cval.phone}
<div>
<button type='submit' onClick={()=>this.handleclick(cval.id)}>Click to view Details</button>
</div>
</div>

)
})
return(
<div>
{newarray}
<CustomerList />

</div>
)
}
}
export default Customers;
CustomerList.js-
class CustomerList extends Component{
render(){
const datalist=  [
{
id: 1,
name: "John Smith",
email: "jsmith@test.com",                                       
phone: "123456789",
city: "bangalore",
state: "karnataka",
country: "India",
organization: "Company 1",
jobProfile: "Software Developer",
additionalInfo: "Has Bought a lot of products before and a high Valu Customer"
},
{
id: 2,
name: 'ABCD',
email: "abcd@test.com",
phone: "987654321",
city: "Mangalore",
state: "karnataka",
country: "India",
organization: "Company 2",
jobProfile: "Software Developer",
additionalInfo: "Buys Products Rarely"
},
{
id: 3,
name: "Tyrion",
email: "tyrion@test.com",
phone: "123412345",
city: "Chennai",
state: "Tamil Nadu",
country: "India",
organization: "Company 3",
jobProfile: "Software Developer",
additionalInfo: "Buys Lots of Products in general"
}
]
const newarraydata= datalist.map((val)=>{       
return(
<div>
{val.name}
{val.email}
{val.phone}
{val.city}
{val.state}
{val.country}
{val.organization}
{val.jobProfile}
{val.additionalInfo}
</div>
)
})
return(

<div>
{newarraydata}
</div>
)
}
}
export default CustomerList;

首先,每当用户单击按钮时,我都要显示此客户列表的详细信息。其次,我不知道该在handlecllick中传递什么。setstate。我可以在屏幕上正常渲染它,但不知道如何在单击按钮时渲染它。我是reajs的初学者。必须感谢你的帮助。

检查沙盒:https://codesandbox.io/s/rough-https-2i54g?file=/src/App.js

您可以使用一个条件语句来确定是否渲染;

<div>
{cval.id === this.state.currentId && (
<CustomerList id={this.state.currentId} />
)}
</div>

您还可以通过设置类似的状态来过滤当前选择的id

constructor(props) {
super(props);
this.state = { currentId: null };
}
handleclick = (id) => {
this.setState({ currentId: id });
};

在Customers组件中,您可以使用状态为"的布尔变量;showList";并且最初将其设置为false。无论何时单击该按钮,都可以将其更改为true或根据其当前值进行切换。然后在render方法内部,而不是直接显示CustomerList组件,使用条件呈现来呈现组件{this.state.showList?:null}

最新更新