react 定義元件變數
阿新 • • 發佈:2018-11-11
react定義變數: constructor(){ super(); this.state={ timer:0 } }
方法:
functionA(){
console.log("this is functionA!");
}
引用 onClick={this.functionA.bind(this)}
eq:計數器
Timer
var React = require('react'); class Timer extends React.Component { constructor(){ super(); this.state={ timer:0, a:"wo shi A" } } tick(){ this.setState({ timer:this.state.timer+1, }) } componentDidMount(){ this.aa = setInterval(()=>{this.tick()},1000); } componentWillUnmount() { clearInterval(this.aa) } outputB(){ console.log("BBBB"); console.log(this.state.a); } render(){ return( <div> <button onClick={this.outputB.bind(this)}>點選列印B</button> <p>{this.state.timer}</p> </div> ) } } module.exports=Timer
文字編輯框:
Editer
var React = require('react'); class Editor extends React.Component{ constructor(){ super(); this.state={ value: 'Type some *markdown* here!', style: { border: '5px solid #666'} } } handleChange() { var content = this.refs.textarea.value; if(content.length >= 10){ this.setState({ value: this.refs.textarea.value, style: { border: '5px solid #666'} }); }else{ this.setState({style: {border: '5px solid #f00'}}) } } render() { return ( <div className="MarkdownEditor"> <h3>Input</h3> <textarea style={this.state.style} onChange={this.handleChange.bind(this)} ref="textarea" defaultValue={this.state.value} /> <h3>Output</h3> <div className="content" dangerouslySetInnerHTML={{ __html: this.state.value }} /> </div> ); } } module.exports = Editor;
在main裡引用
Main
var Header=require("./../pages/Header"); var Timer=require("./Timer"); var Editor=require("./Editor"); class Main extends React.Component{ render () { return( <div> this is MyReact! <Timer/> <Editor/> <Footer/> </div> ) }
ReactDom.render(<Main/>,document.getElementById("main"))