当我单击来自带有isChecked字段的数组的复选框时,没有任何反应。 handleChange()显然不起作用。一切似乎都可以正常映射,因为最初设置为true或false的复选框显示正确。在添加isChecked = {network [i] .isChecked}之前,所有字段都没有选中。但是现在我无法选中或取消选中。我在哪里弄糟?
App.js
import React, {Component} from 'react';
import NetworkArray from './components/NetworkArray';
import {network} from './NetworkData'
import './App.css';
import 'tachyons';
class App extends Component {
constructor() {
super()
this.state = {
network: network,
searchfield:'',
}
this.handleChange=this.handleChange.bind(this);
}
handleChange(id) {
this.setState(prevState => {
const updatedNetwork = prevState.network.map(netw => {
if (netw.id === id) {
netw.isChecked = !netw.isChecked
}
return netw
})
return {
network:updatedNetwork
}
})
}
render() {
const filteredNetwork = this.state.network.filter(netw => {
return netw.lastName.toLowerCase().includes(this.state.searchfield.toLowerCase())
})
return (
<div>
<NetworkArray
network={filteredNetwork}
handleChange = {this.handleChange} />
</div>
)
}
}
export default App;
CardComponent
import React from 'react';
const Card = (props) => {
return(
<div className = 'bg-light-green dib br3 pa3 ma2 grow shadow-5'>
<div>
<h3>{props.name}</h3>
<p>{props.company}</p>
<p>{props.phone}</p>
<p>{props.email}</p>
<p>{props.city}</p>
</div>
<div>
My Network
<input className ="largeCheckbox"
type = "checkbox"
checked={props.isChecked}
onChange={()=> props.handleChange(props.id)}
/>
</div>
</div>
)
}
export default Card;
NetworkArray.js
import Card from './Card';
const NetworkArray = ({network,handleChange}) => {
const cardComponent = network.map((user,i) => {
return(
<Card
key = {network[i].id}
name = {network[i].firstName + ' ' + network[i].lastName}
company = {network[i].company}
phone= {network[i].phone}
email={network[i].email}
city = {network[i].city}
isChecked= {network[i].isChecked}
handleChange={handleChange}
/>
)
})
return (
<div>
{cardComponent}
</div>
)
}
export default NetworkArray;
答案 0 :(得分:1)
您需要将id
道具传递到Card
组件,以便可以将某些东西传递给props.handleChange
:
<Card
id={network[i].id}
key={network[i].id}
name={network[i].firstName + ' ' + network[i].lastName}
company={network[i].company}
phone={network[i].phone}
email={network[i].email}
city={network[i].city}
isChecked={network[i].isChecked}
handleChange={handleChange}
/>