【问题标题】:React Events behavior反应事件行为
【发布时间】:2015-02-21 06:10:51
【问题描述】:

我正在尝试使用React events 访问分配给按钮的自定义“值”,但根据我单击按钮的位置,我会得到不同的结果。我可能可以使用getDOMNode()this.state 来获得所需的结果,但我对如何使用“反应事件”及其行为有点困惑。

最好在像<input> 这样的单个元素上使用合成事件吗?有没有办法使用反应事件来获取按钮的值?

注意:我在 <button> 元素中使用引导 glyphicon。

var Content = React.createClass({
    handleClick: function(e) {
        console.log( e.target );
    },
    render: function() {
        return (
            <div>
                <button type="button" value="button1" className="btn btn-default" onClick={this.handleClick}><span className="glyphicon glyphicon-ok"></span> Submit</button>
            </div>
        )
    }
});

Jsfiddle

console.log(e.target) 结果:

  1. 将鼠标移到字形“复选标记”上,然后单击。

    <span class="glyphicon glyphicon-ok" data-reactid=".0.0.0"></span>
    
  2. 将鼠标移到“提交”一词上并单击

    <span data-reactid=".0.0.1"> Submit</span> 
    
  3. 将鼠标移动到按钮内的任何其他位置,然后单击

    <button type="button" value="button1" class="btn btn-default" data-reactid=".0.0"><span class="glyphicon glyphicon-ok" data-reactid=".0.0.0"></span><span data-reactid=".0.0.1"> Submit</span></button>
    

正如你们所知,我是合成事件和 DOM 行为的新手。任何指导将不胜感激!谢谢。

【问题讨论】:

    标签: javascript events dom reactjs


    【解决方案1】:

    我想你想要e.currentTarget.getAttribute('value')

    使用currentTarget 将获得按钮,因为事件会冒泡到按钮。您正在获取 span 元素,因为您可能会单击 span。这就是target 的值。

    这里还有更新的小提琴:http://jsfiddle.net/v27bqL5y/1/

    【讨论】:

      【解决方案2】:

      另一种方法是使用refs。如果您不想使用 e.currentTarget 之类的东西,这可能是一种更简单的方法。

      见小提琴:http://jsfiddle.net/v27bqL5y/2/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-05
        • 2021-06-21
        • 1970-01-01
        • 1970-01-01
        • 2017-07-14
        • 2015-07-22
        • 1970-01-01
        相关资源
        最近更新 更多