gpt4 book ai didi

javascript - React - 单击
  • 时 onClick 返回 'null undefined'
  • 转载 作者:行者123 更新时间:2023-11-28 14:21:40 24 4
    gpt4 key购买 nike

    我在 React 中创建了一个图像列表。我在屏幕上显示了每个图像的名称,并且希望当有人单击图像名称时将 URL 保存在状态中。

    当我点击其中一个图像名称时,我得到null undefined。我做错了什么?

    import React from 'react'

    const images = [
    { name: 'Image 1', url: 'https://some.com' },
    { name: 'Image 2', url: 'https://thing.com' }
    ]

    class Imglist extends React.Component {
    constructor(props) {
    super(props)

    this.state = {
    url: null
    }
    }

    onClick(event) {
    this.setState(event.value)
    return console.log(this.state.url, event.value)
    }

    render() {

    var that = this

    return (
    <div>
    <ul>
    {images.map(function(element, index) {
    return <li key={index} onClick={that.onClick.bind(that)}>{element.name}</li>
    })}
    </ul>
    </div>
    )
    }
    }

    export default Imglist

    最佳答案

    import React from 'react'

    const images = [
    { name: 'Image 1', url: 'https://some.com' },
    { name: 'Image 2', url: 'https://thing.com' }
    ]

    class Imglist extends React.Component {
    constructor(props) {
    super(props)

    this.state = {
    url: null
    }

    this.onClick = this.onClick.bind(this); // <-- bind early
    }

    onClick(element) {
    // setState is async, so your code does not work. to make it works, add your console log in a callback.

    this.setState({url: element.url}, () => {
    console.log(this.state.url, event.value)
    })
    }

    render() {

    var that = this

    return (
    <div>
    <ul>
    {images.map(function(element, index) { // <-- you can use arrow func, so that you don't need to assign this to that.
    return <li key={index} onClick={() => that.onClick(element)}>{element.name}</li>
    })}
    </ul>
    </div>
    )
    }
    }

    export default Imglist

    关于javascript - React - 单击 <li> 时 onClick 返回 'null undefined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54976215/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com