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;
首先,我想在用户单击按钮时显示此客户列表详细信息。其次,我不知道在 handleclclick 内的 this.setstate 中传递什么。我能够在屏幕上正常渲染它,但不知道如何在按钮单击时渲染它。我是reacjs的初学者。必须感谢您的帮助。
答案 0 :(得分:0)
检查沙箱: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 });
};
答案 1 :(得分:0)
在客户组件中,您可以使用处于“showList”状态的布尔变量,并最初将其设置为 false。每当单击按钮时,您都可以将其更改为 true 或根据其当前值进行切换。 然后在render方法内部而不是直接显示CustomerList组件使用条件渲染来渲染组件 {this.state.showList ? : 空}