反应-单击<li>时onClick返回“ null undefined”

时间:2019-03-04 03:25:03

标签: javascript reactjs onclick

我已经在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

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您的onClick函数应该是

onClick(url) {
  this.setState({url}, () => {
    console.log(this.state.url, url)
   })
}

不需要returnconsole,并且this.setState是async函数,您应该使用回调来获取正确的值。并在arrow function

时使用map
// JSX
{images.map(({name, url}, index) => {
   return <li key={index} onClick={() => this.onClick(url)}>{name}</li>
 })}

答案 2 :(得分:1)

event.target.value用于检索表单值,而不是单击事件。

尝试一下:

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

而您的onClick应该是

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