我有一个名为friends的道具被列为复选框(默认:未选中)。
示例输出:
鲍勃史密斯 汤姆布朗如何保存所有选定名称的ID?
E.g。两者都勾选/选中 - >存储ID 1和2。
这是我到目前为止所做的:
class SelectFriends extends Component {
constructor(props) {
super(props)
this.state = {
SelectedFriendsIds: [],
}
}
render() {
const { SelectedFriendsIds } = this.state
const { userId, friends, addFriendsTo } = this.props
return (
<div>
<SubHeader title="Add Friends..." />
<div>
{friends
.mapEntries(([friendId, frn]) => [
friendId,
<div key={friendId}>
<input
value={friendId}
type='checkbox'
// onChange={ () => console.log("do something")
defaultChecked={false} />
{frn.firstName} {frn.lastName}
</div>,
])
.toList()}
</div>
<div>
<Button style="blue" name="Done" onClick={() => addFriendsTo(SelectedFriendIds, userId)} />
</div>
</div>
)
}
}
export default SelectFriends
答案 0 :(得分:1)
以下是代码的略微简化版本,其中包含新功能handleChange
,每次选中/取消选中复选框时都会调用该功能。
我们获取州的副本并提取selectedFriendsIds
。如果要将状态添加到状态setState
,则会将新值的新数组合并到selectedFriendsIds
中。如果取消选中复选框,则会调用setState
并使用selectedFriendsIds
的过滤副本。
您可能希望运行此代码段整页,因为它会在每次更改后将状态记录到控制台以显示输出。
class SelectFriends extends React.Component {
constructor(props) {
super(props);
this.state = { selectedFriendsIds: [] }
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
const { checked, value } = e.target;
let { selectedFriendsIds } = this.state;
if (checked) {
selectedFriendsIds = [...selectedFriendsIds, value];
} else {
selectedFriendsIds = selectedFriendsIds.filter(el => el !== value);
}
this.setState({ selectedFriendsIds }, () => console.log(this.state));
}
render() {
const { friends } = this.props;
return (
<div>
<h2>Add Friends</h2>
{friends.map(({ friendId, frn }) => {
return (
<div key={friendId}>
<input value={friendId} type="checkbox" onChange={this.handleChange} />{frn}
</div>
);
})}
</div>
)
}
}
const friends = [
{ friendId: 1, frn: 'Bob' },
{ friendId: 2, frn: 'Davros' },
{ friendId: 3, frn: 'Daisy' }
];
ReactDOM.render(
<SelectFriends friends={friends} />,
document.getElementById('container')
);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
&#13;
答案 1 :(得分:1)
您需要检查该值是否已存在于所选列表中,如果不存在,则添加该值除去复选框的值onChange事件。检查下面的示例代码
class SelectFriends extends Component {
constructor(props) {
super(props)
this.state = {
SelectedFriendsIds: [],
}
}
onChange = (val) => {
const SelectedFriendsIds = [...this.state.SelectedFriendsIds];
const presentIndex = SelectedFriendsIds.indexOf(val)
if(presentIndex > 0) {
SelectedFriendsIds.splice(presentIndex, 1);
} else {
SelectedFriendsIds.push(val);
}
this.setState({SelectedFriendsIds})
}
render() {
const { SelectedFriendsIds } = this.state
const { userId, friends, addFriendsTo } = this.props
return (
<div>
<SubHeader title="Add Friends..." />
<div>
{friends
.mapEntries(([friendId, frn]) => [
friendId,
<div key={friendId}>
<input
value={friendId}
type='checkbox'
onChange={ () => this.onChange(friendId)
defaultChecked={false} />
{frn.firstName} {frn.lastName}
</div>,
])
.toList()}
</div>
<div>
<Button style="blue" name="Done" onClick={() => addFriendsTo(SelectedFriendIds, userId)} />
</div>
</div>
)
}
}
export default SelectFriends
答案 2 :(得分:0)
您只需使用 array.push 在check array.filter 上添加ID即可检索单个ID和 array.slice 以删除单个标识。
答案 3 :(得分:0)
可以像这样修改代码
class SelectFriends extends Component {
constructor(props) {
super(props)
this.state = {
SelectedFriendsIds: {}, //CHANGING INTO OBJ FOR EASIER MANIPULATION
}
}
render() {
const { SelectedFriendsIds } = this.state
const { userId, friends, addFriendsTo } = this.props
return (
<div>
<SubHeader title="Add Friends..." />
<div>
{friends
.mapEntries(([friendId, frn]) => [
friendId,
<div key={friendId}>
<input
checked={friendId} //USE CHECKED ALWAYS FOR CHECKBOXES
type='checkbox'
onChange={(e) => {
let x = SelectedFriendsIds;
if (e.target.checked) {
x[friendId] = true;
}
else {
delete x[friendId];
}
this.setState({
SelectedFriendsIds: x
})
}} />
{frn.firstName} {frn.lastName}
</div>,
])
.toList()}
</div>
<div>
<Button style="blue" name="Done" onClick={() => addFriendsTo(SelectedFriendIds, userId)} />
</div>
</div>
)
}
}
export default SelectFriends
如果您需要一些选定的朋友,请使用
Object.keys(this.state.SelectedFriendsIds)
答案 4 :(得分:0)
我想建议对组件的设计进行一些小改进,这也解决了如何有效维护所选朋友ID的状态的问题。坦率地说,没有必要保持选定ID的状态。相反,请保持一个朋友收集状态 - 代表朋友的每个对象都有'选择'属性。这样,您就可以轻松过滤所选的并将此信息发送到上部组件。以下是完整解释此内容的代码段:
import React, { Component } from 'react';
import * as _ from 'lodash';
import PropTypes from 'prop-types';
class FriendsList extends Component {
state = {
friends: []
}
constructor(props) {
super(props);
this.onAdd = this.onAdd.bind(this);
this.state.friends = [ {id: 1, name: 'John', selected: false},
{ id: 2, name: 'Ally', selected: false},
{ id: 3, name: 'Becky', selected: false},
{ id: 4, name: 'Frank', selected: false},
{ id: 5, name: 'Mark', selected: true},
{ id: 6, name: 'Alice', selected: true}
];
}
onCheckboxChange(event, n) {
n.selected = !n.selected;
this.forceUpdate();
}
onAdd() {
const selectedFriends = _.filter( this.state.friends, (friend) => {
return friend.selected === true;
});
this.props.onAdd(selectedFriends);
}
render() {
const { friends } = this.state;
return (
<div>
{friends.map(n => {
return (
<div key={n.id}>
{n.name} <input type="checkbox" onChange={(event) => this.onCheckboxChange(event, n)} checked={n.selected}/>
</div>
);
})}
<button onClick={this.onAdd}>Add Friends</button>
</div>
);
}
}
FriendsList.propTypes = {
onAdd: PropTypes.func,
};
export default FriendsList;