如何在React.js中的div上使用onClick [英] How to use onClick with divs in React.js

查看:95
本文介绍了如何在React.js中的div上使用onClick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个非常简单的应用程序,您可以单击正方形div将其颜色从白色更改为黑色.但是,我遇到了麻烦.我想使用onClick函数来允许用户单击正方形以更改其颜色,但是它似乎没有用.我已经尝试过使用span和空p标签,但这也不起作用.

I'm making a very simple application where you can click on square divs to change their color from white to black. However, I'm having trouble. I'd like to use the onClick function to allow a user to click on a square to change its color, but it doesn't seem to be working. I've tried using spans and empty p tags, but that doesn't work either.

这是有问题的代码:

var Box = React.createClass({
    getInitialState: function() {
        return {
            color: 'white'
        };
    },

    changeColor: function() {
        var newColor = this.state.color == 'white' ? 'black' : 'white';
        this.setState({
            color: newColor
        });
    },

    render: function() {
        return (
            <div>
                <div
                    style = {{background: this.state.color}}
                    onClick = {this.changeColor}
                >
                </div>
            </div>
        );
    }
});

这是我在CodePen上的小项目的链接. http://codepen.io/anfperez/pen/RorKge

Here's a link to my small project on CodePen. http://codepen.io/anfperez/pen/RorKge

推荐答案

有效

var Box = React.createClass({
    getInitialState: function() {
        return {
            color: 'white'
        };
    },

    changeColor: function() {
        var newColor = this.state.color == 'white' ? 'black' : 'white';
        this.setState({ color: newColor });
    },

    render: function() {
        return (
            <div>
                <div
                    className='box'
                    style={{background:this.state.color}}
                    onClick={this.changeColor}
                >
                    In here already
                </div>
            </div>
        );
    }
});

ReactDOM.render(<Box />, document.getElementById('div1'));
ReactDOM.render(<Box />, document.getElementById('div2'));
ReactDOM.render(<Box />, document.getElementById('div3'));

在您的CSS中,删除您拥有的样式并将其放置

and in your css, delete the styles you have and put this

.box {
  width: 200px;
  height: 200px;
  border: 1px solid black;
  float: left;
}

您必须设置要在其上调用 onClick 的实际div的样式.给div一个className,然后设置其样式.还请记住删除将 App 渲染到dom中的此块,未定义App

You have to style the actual div you are calling onClick on. Give the div a className and then style it. Also remember to remove this block where you are rendering App into the dom, App is not defined

ReactDOM.render(<App />,document.getElementById('root'));

这篇关于如何在React.js中的div上使用onClick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆