前端开发ReactJs学习(环境配置,一个hello world)

安卓前端开发流程
安卓前端开发编辑器
安卓前端开发收入怎么样

一:配置环境
1.下载npm: https://nodejs.org/en/download/ 并安装
2.此处安装在目录:D:\Program Files\nodejs
3.配置环境变量:变量名:NODE_PATH 值:D:\Program Files\nodejs\node_modules
4.打开cmd,输入node -v 如果出现对应版本号则成功

二:一个测试程序
初学者练习见官网:http://reactjs.cn/react/docs/getting-started.html 下载
在examples目录下新建一个test目录练习:Hello world………

此处有两种方法:
1.引用JSXTransformer.js来在浏览器中进行代码转换(由于reactjs应用的是jsx语法,故而需要一个脚本来解析:jsx语法入口
新建Index.html:
html 代码片段

<!DOCTYPE html>
<html lang=”en”>
    <head>
        <meta charset=”UTF-8″ />
        <title>Document</title>
        <script src=”../../build/react.js”></script>
        <script src=”../../build/JSXTransformer.js”></script>
    </head>
    <body>
        <div id=”example”></div>
        <script type=”text/jsx”>
            React.render(
             <h1>Hello,world</h1>,
             document.getElementById(‘example’) //此处要使用js原生的方法来获取容器元素
             )
        </script>
    </body>
</html>

2.离线转换
使用之前装的npm来进行离线转换,这样直接引用转换完的js文件即可
如何进行离线转换呢?
1).将之前的jsx代码独立一个js文件,这里命名为test.js
jsx 代码片段

React.render(<h1>Hello, world!</h1>, document.getElementById(‘example’))

那么相对应的index.html代码:(几点需要注意,【1】JSXTransformer.js这个文件无须引用,因为接下来会使用npm进行离线转换。【2】引用了一个js:<script src=”../testResult/test.js”></script>
此处引用的js是即将使用npm处理完毕后的js文件)

html 代码片段

<!DOCTYPE html>
<html lang=”en”>
    <head>
        <meta charset=”UTF-8″ />
        <title>Document</title>
        <script src=”../../build/react.js”></script>
    </head>
    <body>
        <div id=”example”></div>
        <script src=”../testResult/test.js”></script>
    </body>
</html>

2).使用jsp –watch命令进行转换(此处官方示例给的是jsx –watch src/ build/ 即监听此文件夹并将修改后的js文件也保存至此,为了更加清晰将解析后的js文件另放一个文件夹并引用次文件:
jsx –watch E:\test\react-0.13.0\react-0.13.0\examples\test E:\test\react-0.13.0\react-0.13.0\examples\testResult)
这样就得到了转换之后的js文件并且页面中直接引用次文件即可:
javascript 代码片段

React.render(
    React.createElement(‘h1’, null, ‘Hello, world!’),
    document.getElementById(‘example’),
)

二:一些官方示例
示例来源: http://reactjs.cn/react/docs/tutorial.html
Reactjs的一大特点就是组件化,下面在test.js中实验一些官方示例,熟悉一下reactjs
1)简单组件

html 代码片段

//组件1
var CommentList = React.createClass({
    render: function() {
        return (
            <div className=”commentList”>Hello, world! I am a CommentList.</div>
        )
    },
})
//组件2
var CommentForm = React.createClass({
    render: function() {
        return (
            <div className=”commentForm”>Hello, world! I am a CommentForm.</div>
        )
    },
})
//组件3
var CommentBox = React.createClass({
    render: function() {
        return (
            <div className=”commentBox”>
                <h1>Comments</h1>
                <CommentList />
                <CommentForm />
            </div>
        )
    },
})
//组件4
var FinalBox = React.createClass({
    render: function() {
        return <CommentBox />
    },
})
//最后显示FinalBox组件中的内容,而FinalBox中引用的是CommentBox组件
//故此处直接使用CommentBox是一样的效果
React.render(<FinalBox />, document.getElementById(‘example’))

组件化的模式确实很好,方便组件复用提高效率,但是要注意reactjs使用驼峰命名法(e.g: CamelName),如果将FinalBox改成finalBox(小驼峰?)并且在最后使用<finalBox/>会发现不会显示任何东西

2)使用属性props
官方解释:让我们创建 Comment 组件,该组件依赖于从父级传入的数据。从父组件传入的数据会做为子组件的 属性( property ) ,这些 属性( properties ) 可以通过 this.props 访问到。使用属性( props ),我们就可以读到从 CommentList 传到 Comment 的数据,然后渲染一些标记

html 代码片段

var CommentList = React.createClass({
    render: function() {
        return (
            <div className=”commentList”>
                <Comment author=”Pete Hunt”>This is one comment</Comment>
                <Comment author=”Jordan Walke”>
                    This is *another* comment
                </Comment>
            </div>
        )
    },
})
var Comment = React.createClass({
    render: function() {
        return (
            <div className=”comment”>
                <h2 className=”commentAuthor”>{this.props.author}</h2>
                {this.props.children}
            </div>
        )
    },
})
React.render(<CommentList />, document.getElementById(‘example’))

3)接入数据模型
javascript 代码片段

var data = [
    { author: ‘Tom’, text: ‘Test <em>text</em> Tom>’, year: 2015 },
    { author: ‘Peter’, text: ‘Test text Peter’, year: 2016 },
]
var CommentForm = React.createClass({
    render: function() {
        return (
            <div className=”commentForm”>Hello, world! I am a CommentForm.</div>
        )
    },
})
var Comment = React.createClass({
    render: function() {
        return (
            <div className=”comment”>
                <h2 className=”commentAuthor”>{this.props.author}</h2>
                {marked(this.props.children.toString(), { sanitize: true })}
                {this.props.children.toString()}
            </div>
        ) //使用marked方法需要引入 <script src=”https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.2/marked.min.js”></script>
    }, //指定sanitize:true表示转义掉html标签(保护免受xss攻击)
}) //使用toString会以逗号拼接,可以使用Join方法替代
var CommentList = React.createClass({
    render: function() {
        var commentNodes = this.props.data.map(function(comment) {
            return (
                <Comment author={comment.author}>
                    {comment.text}——{comment.year}
                </Comment>
            ) //调用map方法循环数据,每条循环出来的数据都传入Comment组件处理
        })
        return <div className=”commentList”>{commentNodes}</div>
    },
})
var CommentBox = React.createClass({
    render: function() {
        return (
            <div className=”commentBox”>
                <h1>Comments</h1>
                <CommentList data={this.props.data} />
                <CommentForm />
            </div>
        ) //调用CommentList并传入数据
    },
})
React.render(
    <CommentBox data={data} />, //调用组件CommentBox并传入数据
    document.getElementById(‘example’),
)

4)从服务器获取数据
后台使用asp.net mvc模拟
html 代码片段

//后台代码
[AllowAnonymous]
[HttpGet]
publicActionResultuserInfo(stringcallBack){
List<info> infoList = new List<info>();
infoList.Add(new info {author=”Tom”,text=”This is Tom”,year=2015 });
infoList.Add(new info { author = “Peter”, text = “This is Peter”, year = 2016 });
string str = new JavaScriptSerializer().Serialize(infoList);
string result = string.Format(“{0}({1})”, callBack, str);
returnContent(result);
}
publicclassinfo
{
public string author { get; set;}
public string text { get; set;}
public int year { get; set;}
}
//testjs代码
//引用jquery使用jquery的ajax方法跨域获取json数据
var CommentBox = React.createClass({
getInitialState:function(){
return{data:[]};
},
loadCommentsFromServer:function(){
$.ajax({
url:this.props.url,
type:”GET”,
async:false,
dataType:”jsonp”,
success:function(data){
this.setState({data: data});
}.bind(this),
error:function(xhr, status, err){
console.error(this.props.url, status, err.toString());
}.bind(this),
});
},
componentDidMount:function(){
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer,this.props.pollInterval);
},
render:function(){
return(
<divclassName=”commentBox”>
<CommentListdata={this.state.data}/>
</div>
);
}//getInitialState设置初始化的状态
});//loadCommentsFromServer获取服务器上的数据,componentDidMount每隔pollInterval时间调用loadCommentsFromServer方法
var CommentList = React.createClass({
render:function(){
var commentNodes =this.props.data.map(function(comment){
return(
<Commentauthor={comment.author}>
{comment.text}:{comment.year}
</Comment>
);
});
return(
<divclassName=”commentList”>
{commentNodes}
</div>
);
}
});
var Comment = React.createClass({
render:function(){
return(
<divclassName=”comment”>
<h2className=”commentAuthor”>
{this.props.author}
</h2>
<spanstyle={{color:”red”}}>{this.props.children.join(“”)}</span>
</div>
);
}
});
React.render(
<CommentBoxurl=”https://www.rokub.com:17955/home/userInfo”pollInterval={2000}/>,
document.getElementById(‘example’)
)

5)向服务器提交数据
html 代码片段

//后台c#代码
public static List<info> infoList = new List<info>() { new info { author = “Tom”, text = “This is Tom”, year = 2015 }, new info { author = “Peter”, text = “This is Peter”, year = 2016 } };
定义一个静态变量存储数据;
[HttpPost]
publicActionResultsubData(infoinfo)
{
infoList.Add(info);
returnContent(“success”);
}
//test.js代码
var CommentBox = React.createClass({
getInitialState:function(){
return{data:[]};
},
loadCommentsFromServer:function(){
$.ajax({
url:this.props.url,
type:”GET”,
async:false,
dataType:”jsonp”,
success:function(data){
this.setState({data: data});
}.bind(this),
error:function(xhr, status, err){
console.error(this.props.url, status, err.toString());
}.bind(this),
});//定时从服务器获取数据
},
handleCommentSubmit:function(comment){
$.ajax({
url:this.props.subUrl,
dataType:’json’,
type:’POST’,
data: comment,
success:function(data){
this.setState({data: data});
}.bind(this),
error:function(xhr, status, err){
console.error(this.props.subUrl, status, err.toString());
}.bind(this)
});//提交数据
},
componentDidMount:function(){
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer,this.props.pollInterval);
},
render:function(){
return(
<divclassName=”commentBox”>
<CommentListdata={this.state.data}/>
<CommentFormonCommentSubmit={this.handleCommentSubmit}/>
</div>
);
}//实际调用handleCommentSubmit方法
});
var CommentList = React.createClass({
render:function(){
var commentNodes =this.props.data.map(function(comment){
return(
<Commentauthor={comment.author}>
{comment.text}:{comment.year}
</Comment>
);
});
return(
<divclassName=”commentList”>
{commentNodes}
</div>
);
}
});
var Comment = React.createClass({
render:function(){
return(
<divclassName=”comment”>
<h2className=”commentAuthor”>
{this.props.author}
</h2>
<spanstyle={{color:”red”}}>{this.props.children.join(“”)}</span>
</div>
);
}
});
var CommentForm = React.createClass({
handleSubmit:function(e){
e.preventDefault();
var author =this.refs.author.getDOMNode().value.trim();
var text =this.refs.text.getDOMNode().value.trim();
var year =this.refs.year.getDOMNode().value.trim();
console.log(author+”-“+text);
if(!text ||!author){
return;
}
this.props.onCommentSubmit({author: author,text: text,year:year});
this.refs.author.getDOMNode().value =”;
this.refs.text.getDOMNode().value =”;
this.refs.year.getDOMNode().value =”;
return;
},//获取表单数据,调用onCommentSubmit并将数据传入
render:function(){
return(
<formclassName=”commentForm”onSubmit={this.handleSubmit}>
<inputtype=”text”placeholder=”Your name”ref=”author”/>
<inputtype=”text”placeholder=”Say something…”ref=”text”/>
<inputtype=”text”placeholder=”year”ref=”year”/>
<inputtype=”submit”value=”Post”/>
</form>
);
}
});
React.render(
<CommentBoxurl=”https://www.rokub.com:17955/home/userInfo”subUrl=”https://www.rokub.com:17955/home/subData”pollInterval={2000}/>,
document.getElementById(‘example’)
);
//html代码
<!DOCTYPE html>
<html lang=”en”>
<head>
<metacharset=”UTF-8″>
<title>Document</title>
<scriptsrc=”../../build/react.js”></script>
<scriptsrc=”../../build/marked.min.js”></script>
<scriptsrc=”../../build/jquery-1.8.2.min.js”></script>
<scripttype=”text/javascript”></script>
</head>
<body>
<divid=”example”></div>
<scriptsrc=”../testResult/test.js”></script>
</body>
</html

或者配合jquery将数据序列化后传至后台:
html 代码片段

jsx:
    <form onSubmit={this.handleSubmit}>
        <input name=”author” type=”text” ref=”author” />
        <input name=”text” type=”text” ref=”text” />
        <input name=”year” type=”text” ref=”year” />
        <input type=”submit” value=”提交” />
    </form>
         handleSubmit:function(e){
e.preventDefault();
            console.log(“entered”);
            var data = $(“form”).serialize();
            this.props.onCommentSubmit(data);
            }
         handleCommentSubmit:function(data){
$.ajax({
url:”https://www.rokub.com:17955/home/subData”,
            dataType:”text”,
            type:”POST”,
            data:data,
            success:function(result){
console.log(“success:”+result);
            },
            error(function(result) {
console.log(“failed:”+result);
            });
            })

三:组件间传值
参考网址: http://ctheu.com/2015/02/12/how-to-communicate-between-react-components/

1)父组件传值给子组件(利用props,缺点是如果层级过多,则每一级都需要将父级传入的Props属性向下再传递)
html 代码片段

//父组件
var TestContainer = React.createClass({
    render: function() {
        return <TestContext text=”This is a test” />
    },
})
//子组件
var TestContext = React.createClass({
    render: function() {
        var text = this.props.text
        return <label>{text}</label>
    },
})
React.render(<TestContainer />, document.getElementById(‘example’))

2)子组件传值给父组件(调用回调函数传值,其实还是从props中获取……)
html 代码片段

var TestContainer = React.createClass({
    getInitialState: function() {
        return {
            data: ‘This is an initial data’,
        }
    },
    callbackFunc: function(data) {
        this.setState({
            data: data,
        })
    },
    render: function() {
        return (
            <div>
                <TestContext callback={this.callbackFunc} />
                <label style={{ color: ‘red’ }}>{this.state.data}</label>
            </div>
        )
    },
})
var TestContext = React.createClass({
    onTextChange: function() {
        var data = document.getElementById(‘data’).value
        this.props.callback(data)
    }, //onTextChange调用父组件传过来的callback方法并将数据传入</p>
    render: function() {
        return <input id=”data” type=”text” onChange={this.onTextChange} /> //onChange的时候调用onTextChange方法
    },
})
React.render(<TestContainer />, document.getElementById(‘example’))

3)context
根据参考文章中的方法可以使用上下文context来进行传递,文中给出的代码:

html 代码片段

var MyContainer = React.createClass({
    getChildContext: function() {
        // it exposes one property “text”, any of the components that are
        // rendered inside it will be able to access it
        return { text: ‘Where is my son?’ }
    },
    // we declare text is a string
    childContextTypes: {
        text: React.PropTypes.string,
    },
    render: function() {
        // no props to pass down
        return <Intermediate />
    },
})
var Intermediate = React.createClass({
    render: function() {
        // this component has no props
        return <Child />
    },
})
var Child = React.createClass({
    // we declare we want to read the .text property of the context
    contextTypes: {
        text: React.PropTypes.string,
    },
    render: function() {
        // this component has access to the current context
        // exposed by any of its parent
        return <span>{this.context.text}</span>
    },
})

但是根据文中所说,此方法在官方文档中尚未给出正式的文档说明
使用此方法能够被子组件所共享,并通过调用this.context获取
注意点:
1.在父组件(外层组件?)定义getChildContext 并返回一个js对象作为context
2.在父组件(外层组件?)定义childContextTypes 并为context中的每个属性都定义类型
3.在子组件(内层组件?)定义contextTypes并指明要从context中读取的数据

安卓开发 前端 哪个
安卓开发前端后端
前端安卓开发工资
» 本文来自:前端开发者 » 《前端开发ReactJs学习(环境配置,一个hello world)》
» 本文链接地址:https://www.rokub.com/7442.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!