繁体   English   中英

我怎样才能在 React 中获取这个 id?

[英]How can I grab this id in React?

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

(id被抓取到onClick后,会更新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

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

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

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

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

您可以在 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)}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM