ReactJS:onClick更改元素 [英] ReactJS: onClick change element

查看:442
本文介绍了ReactJS:onClick更改元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习React并有一个问题。

I've just started learning React and have a question.

我想执行以下操作:

如果用户点击了一个段落,我想更改元素到预填充段落内容的输入字段。
(最终目标是直接编辑,如果用户具有某些特权)

If a user clicks on a paragraph I want to change the element to an input field that has the contents of the paragraph prefilled. (The end goal is direct editing if the user has certain privileges)

我来得这么远,但我完全不知所措。

I'm come this far but am totally at a loss.

var AppHeader = React.createClass({
    editSlogan : function(){
        return (
            <input type="text" value={this.props.slogan} onChange={this.saveEdit}/>
         )
    },
    saveEdit : function(){
        // ajax to server
    },
    render: function(){
        return (
            <header>
                <div className="container-fluid">
                    <div className="row">
                        <div className="col-md-12">
                            <h1>{this.props.name}</h1>
                            <p onClick={this.editSlogan}>{this.props.slogan}</p>
                        </div>
                    </div>
                </div>
            </header>
        );
    }
});

如何从 editSlogan 功能?

推荐答案

如果我理解你的问题,你想在onClick事件的情况下呈现不同的元素。

If I understand your questions correctly, you want to render a different element in case of an "onClick" event.

这是反应状态的一个很好的用例。

This is a great use case for react states.

采取以下示例

React.createClass({ 
    getInitialState : function() {
       return { showMe : false };
    },
    onClick : function() {
       this.setState({ showMe : true} );
    },
    render : function() {
        if(this.state.showMe) { 
            return (<div> one div </div>);
        } else { 
            return (<a onClick={this.onClick}> press me </a>);
        } 
    }
})

这将改变组件状态,并使React呈现div而不是a-tag。当组件状态被改变时(使用setState方法),React计算它是否需要重新渲染自己,并且在这种情况下,它需要重新渲染组件的哪些部分。

This will change the components state, and makes React render the div instead of the a-tag. When a components state is altered(using the setState method), React calculates if it needs to rerender itself, and in that case, which parts of the component it needs to rerender.

更多关于州
https://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html

这篇关于ReactJS:onClick更改元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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