簡體   English   中英

如何使用用戶數組和 axio 在反應 js 中調用復選框中的 onchange function?

[英]How can I call onchange function in checkboxes using a user array and axio get in react js?

我試圖在復選框中獲取一個用戶數組,這個用戶數組的元素來自 JSON 占位符。 我想在帶有 onchange 屬性的復選框中顯示這些值,但不知何故它什么也沒顯示。 這是我到目前為止所做的。

在這里,我已經初始化了 state 並且在句柄單擊中具有e中的值,但它沒有出現在復選框上我得到的一個建議是為每個元素創建單獨的更改處理程序,但我如何才能在更改時分別獲取它們。 我已將 state 初始化為 { users: [] }

    componentDidMount(){
      axios.get('https://jsonplaceholder.typicode.com/users')
      .then (res => {
        console.log(res)
        this.setState({
          users: res.data
        })
      })
    }

    handleChange = (e) => {
      e.target.value;
      console.log(e)
      debugger
    }


          <div className="multiselect">
        <div className="selectBox">
          <select>
            <option>Select an option</option>
          </select>
          <div className="overSelect" ></div>
        </div>

        <div id="checkboxes">
          <label htmlFor ="one">
            <input type="checkbox" checked={this.state.users} id="one" onChange={(e) => this.props.handleChange("users", e)} /></label>

        </div>
      </div>
        </Fragment> 

我想你想要這樣的東西。 在您的用戶集合中,您需要找到正在切換的用戶,切換isSelected鍵,然后設置 state。 checked的鍵在您的render調用中查找user.isSelected 它不需要首先定義,因為undefined將評估為 false。

class App1 extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            users: []
        };
    }

    handleChange(user) {
        // get the user id
        const userId = user.id;

        // check the state, if a user is selected, toggle it
        this.setState(prevState => ({
            users: prevState.users.map(usr => {
                usr.id === userId
                    ? { ...usr, isSelected: !usr.isSelected }
                    : usr;
            })
        }));
    }

    render() {
        const { users } = this.state;

        return (
            <div>
                {Array.isArray(users) &&
                    users.length &&
                    users.map((u, idx) => {
                        <div key={`${idx}-${u.id}`}>
                            <label htmlFor={`${idx}-${u.id}`}>{u.name}</label>
                            <input
                                type="checkbox"
                                checked={u.isSelected}
                                onChange={() => this.handleChange(u)}
                            />
                        </div>;
                    })}
            </div>
        );
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM