React父子组件相互传值
先看效果
代码演示
创建InputView子组件
import React, {Component} from 'react'
export default class InputView extends Component{
constructor(props){
super(props)
}
static defaultProps = {
type: 'default', //输入类型默认
}
render() {
return (
<div>
<span>{this.props.leftTitle}</span>
<input onChange={this.props.inputViewChange} type={this.props.type}/>
</div>
);
}
}
在父组件中使用
import React from 'react'
import InputView from '../../components/InputView'
export default class Home extends React.Component{
constructor(props){
super(props)
}
inputMobile = (event) => {
console.log('手机号' + event.target.value)
}
inputPwd = (event) => {
console.log('密码' + event.target.value)
}
render() {
return (
<div style={{marginLeft: 20, marginRight: 20}}>
<InputView leftTitle='手机号' inputViewChange={this.inputMobile}/>
<InputView leftTitle='密码' type='password' inputViewChange ={this.inputPwd}/>
</div>
)
}
}