简体   繁体   English

如何在 React.js 中使用带有 div 的 onClick

[英]How to use onClick with divs in React.js

I'm making a very simple application where you can click on square divs to change their color from white to black.我正在制作一个非常简单的应用程序,您可以在其中单击方形 div 将它们的颜色从白色更改为黑色。 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.我想使用 onClick 函数来允许用户点击一个方块来改变它的颜色,但它似乎不起作用。 I've tried using spans and empty p tags, but that doesn't work either.我试过使用跨度和空 p 标签,但这也不起作用。

Here is the code in question:这是有问题的代码:

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>
        );
    }
});

Here's a link to my small project on CodePen.这是我在 CodePen 上的小项目的链接。 http://codepen.io/anfperez/pen/RorKge http://codepen.io/anfperez/pen/RorKge

This works这有效

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'));

and in your css, delete the styles you have and put this并在您的 css 中,删除您拥有的样式并将其放入

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

You have to style the actual div you are calling onClick on.您必须设置调用onClick的实际 div 的样式。 Give the div a className and then style it.给 div 一个 className,然后设置它的样式。 Also remember to remove this block where you are rendering App into the dom, App is not defined还要记得把你渲染App到 dom 的这个块去掉,App 没有定义

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

For future googlers (thousands have now googled this question) :对于未来的谷歌人(数千人现在已经用谷歌搜索了这个问题)

To set your mind at ease, the onClick event does work with divs in react, so double-check your code syntax.为了让您放心, onClick事件确实在反应中与 div 一起使用,因此请仔细检查您的代码语法。

These are right:这些是对的:

<div onClick={doThis}>
<div onClick={() => doThis()}>

These are wrong:这些是错误的:

<div onClick={doThis()}>
<div onClick={() => doThis}>

(and don't forget to close your tags... Watch for this: (不要忘记关闭你的标签......注意这一点:

<div onClick={doThis}

missing closing tag on the div) div 上缺少结束标记)

Your box doesn't have a size.你的盒子没有尺寸。 If you set the width and height, it works just fine:如果你设置宽度和高度,它工作得很好:

 var Box = React.createClass({ getInitialState: function() { return { color: 'black' }; }, changeColor: function() { var newColor = this.state.color == 'white' ? 'black' : 'white'; this.setState({ color: newColor }); }, render: function() { return ( <div> <div style = {{ background: this.state.color, width: 100, height: 100 }} onClick = {this.changeColor} > </div> </div> ); } }); ReactDOM.render( <Box />, document.getElementById('box') );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id='box'></div>

The Following code works now !!!以下代码现在有效!!!

const test = () => {
const onClick = () => console.log('hi');

return (
<div onClick={onClick} aria-hidden="true">
  Content here
</div>
)};

虽然这可以通过 react 来完成,但请注意,将 onClicks 与 div(而不是按钮或锚点,以及其他已经具有点击事件行为的)一起使用是不好的做法,应该尽可能避免。

I just needed a simple testing button for react.js.我只需要一个简单的 react.js 测试按钮。 Here is what I did and it worked.这就是我所做的,并且奏效了。

function Testing(){
 var f=function testing(){
         console.log("Testing Mode activated");
         UserData.authenticated=true;
         UserData.userId='123';
       };
 console.log("Testing Mode");

 return (<div><button onClick={f}>testing</button></div>);
}

This also works:这也有效:

I just changed with this.state.color==='white'?'black':'white' .我只是改变了this.state.color==='white'?'black':'white'

You can also pick the color from drop-down values and update in place of 'black';您还可以从下拉值中选择颜色并更新为“黑色”;

( CodePen ) (代码笔)

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

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