【问题标题】:How can I grab this id in React?我怎样才能在 React 中获取这个 id?
【发布时间】:2020-03-09 20:14:53
【问题描述】:

我试图让 React 从一个从 dialog.json 文件映射的 Button 组件中获取 id。在浏览器中检查时,该 ID 正确位于 Button 标记中。但我不确定如何在点击时抓住它。

(onClick 抓取id 后,会更新State 并从下一个dialog.json 呈现Text 和Buttons)

import React, { Component } from 'react';
import API from '../../utils/API';
import './style.css';
import dialog from './dialog.json';
import Button from '../../components/Button';
import Text from '../../components/Text';

class Game extends Component {
    state = {
        userID: "", //user logged in
        currentLine: dialog[0]
    }

    handleClick = () => {
        alert('Your next Line is: ' + this.id);
        console.log(dialog[0]);
        this.setState({
            currentLine: dialog[this.id]
        })
    }

    componentDidMount() {
        API.getMyDude(this.props.username).then(myDude => {
            this.setState({
                userID: myDude
            })
        })
        // this.startGame();
    }


    render() {
        return (
            <div>
                <br />
                <br />
                {/* {console.log(textNodes[0])} */}
                < Text text={this.state.currentLine.text} />
                <br />
                < div >
                    {this.state.currentLine.options.map(option => (
                        // console.log(option.nextText),
                        < Button
                            option={option.text}
                            id={option.nextText}
                            handleClick={this.handleClick}
                        />
                    ))}
                </div >
            </div >
        )
    }
}
export default Game

此外,欢迎提供任何其他提示或技巧!

【问题讨论】:

    标签: javascript reactjs components setstate


    【解决方案1】:

    您需要将点击事件传递给 handleClick 函数。

    handleClick = (event) => {
        alert('Your next Line is: ' + event.target.id);
        console.log(dialog[0]);
        this.setState({
            currentLine: dialog[event.target.id]
        })
    }
    

    【讨论】:

      【解决方案2】:

      您可以尝试将"{option.nextTest}" 作为参数传递给handleClick 函数。

      【讨论】:

        【解决方案3】:

        您可以在 Button 组件中获取 id。事实上,您可以在您的方法稍作更改后将 handleClick 作为道具(处理程序)传递给 Button:

            handleClick = id => {
                alert('Your next Line is: ' + id);
                console.log(dialog[0]);
                this.setState({
                    currentLine: dialog[id]
                })
            }
        

        在您的 Button 组件中,您应该将 id (props) 作为参数传递给处理程序 (props),例如:

        onClick = {()=>props.handler(props.id)}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-01-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-11-28
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多