【问题标题】:Save each index into each button将每个索引保存到每个按钮中
【发布时间】:2020-10-09 09:17:11
【问题描述】:

我目前正在开发井字游戏,并希望在每个按钮中显示索引,如下所示。我现在正在使用 React。

<button id="button" index="0" nav-selectable="true" class="Square_Square__1MfjH"></button>
<button id="button" index="1" nav-selectable="true" class="Square_Square__1MfjH"></button>
...
<button id="button" index="8" nav-selectable="true" class="Square_Square__1MfjH"></button>

这是我的代码:

const Square = (props) => {
    return (
        <div>
            <button 
                id="button"
                nav-selectable="true"
                key={props.index} // Display this in the button
                className={classes.Square} 
                onClick={() => { props.onClick(); }}
                >
                {props.value}
            </button>
        </div>
    )
}
class Board extends Component {
    renderSquare(i) {
        return <Square 
            index={i} // Take the i from below (0,1,2,3,4,5,6,7,8)
            value={this.props.squares[i]}        
            onClick={() => { this.props.onClick(i); }}
            />;
    }

    render() {
        return (
            <div>
                <div className={classes.Board}>
                    {this.renderSquare(0)}
                    {this.renderSquare(1)}
                    {this.renderSquare(2)}
                </div>
                <div className={classes.Board}>
                    {this.renderSquare(3)}
                    {this.renderSquare(4)}
                    {this.renderSquare(5)}
                </div>
                <div className={classes.Board}>
                    {this.renderSquare(6)}
                    {this.renderSquare(7)}
                    {this.renderSquare(8)}
                </div>
            </div>
        )
    }
}

但是,这种方法似乎不起作用。谁能帮我吗?谢谢!

【问题讨论】:

  • 索引应该是唯一的,所以你不应该使用 id="button" 而是使用类似 id="button-index" ,其中 index 是你的数字
  • 您是否只是想在按钮 上显示索引,例如文本所在的位置?目前尚不清楚您要做什么。此外,元素id 属性应该是全局唯一的。
  • 你想在内容中显示index还是仅仅作为一个按钮的道具?
  • 我只想在浏览器中像这样这样显示在按钮上,所以可以从其他js中选择

标签: javascript reactjs


【解决方案1】:

如果你想要它作为一个属性,你可以使用index 或data-index。

将您的方形示例更改为:

<button 
  id="button"
  nav-selectable="true"
  key={props.index} // Display this in the button
  index={props.index}
  className={classes.Square} 
  onClick={() => { props.onClick(); }}
>
  {props.value}
</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    • 2019-02-01
    • 2016-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多