//1.function方式组件
function MyAddress(props) {
return <h1 style={MyStyle}>第一个function组件:{props.parameter1}</h1>
}
function MyName(props) {
return <h1 style={MyStyle}>第二个function组件:{props.parameter2}</h1>
}
const MyStyle = {//添加样式
color: "blue"
}
//最后:渲染引擎ReactDOM.render
ReactDOM.render(
<div>
//标签方式引用组件,并props传递参数
<MyAddress parameter1="[这是=props1参数传递]"/>,
<MyName parameter2="<这是=propos2参数传递>"/>,
</div>,
document.getElementById(‘example‘)
);
-----------------------------------------------------------------------
//Class组件(state):必有extends,render,return!!!
class WebSite extends React.Component {
constructor() {//初始化构造器
super();//指父级
this.state = {//指此插件.状态参数state
name: "菜鸟教程"
}
}
render() {//组件级渲染
return (
<div>
<Name name={this.state.name} />
</div>
);
}
}
//嵌套组件
class Name extends React.Component {
render() {
return (//this.props.实际渲染时传入参数,可以直接点出(<Name name={this.state.name} />)
<h1>{this.props.name}</h1>
);
}
}
ReactDOM.render(
<WebSite />,
document.getElementById(‘example‘)
);
-----------------------------------------------------------------------
class TextButton extends React.Component {
constructor() {//初始化构造器
super();//指父级
this.update = this.update.bind(this);//构造器内部指定.bind(this)
this.state = {//指此插件.状态参数state
p1: "传递点击按钮事件参数this.state.p1"
}
}
update() {//构造器内部指定.bind(this)
this.props.onChange(‘小明名字改了‘)//DoSomeThing
}
// 这个语法确保了 `this` 绑定在 handleClick 中
handleClick = () => {//定义一个按钮点击触发的函数
alert(this.state.p1);
}
render() {
return (
<button onClick={this.handleClick}>
Click me
</button>
);
}
}
ReactDOM.render(
<TextButton />,
document.getElementById(‘example‘)
);
// 表单
// onchange配合value
class Child extends React.Component {
state = {
name: ‘小明‘
}
constructor(props) {
super(props)
this.update = this.update.bind(this)
}
update(e) {
this.setState({
name: e.target.value
})
}
render() {
return (<div>
<input onChange={this.update} value={this.state.name} />
</div>)
}
}
ReactDOM.render(
<Child />,
document.getElementById(‘example‘)
);
原文:https://www.cnblogs.com/jsll/p/13502280.html