react组件认识使用&组件提升解析

认识组件

react组件使用

import NameCard from './components/NameCard.js';
class App extends Component {
    
    
  constructor(props){
    
    
    super(props);
    this.state = {
    
    
      obj:{
    
    
        name:'std',
        number:123,
      }
    }
  }

  render() {
    
    
    return (
      <div className="App">
        <NameCard content={
    
    this.state.obj}></NameCard>
      </div>
    );
  }
}

NameCard组件:

render(){
    
    
    return (
        <div>
            <h4>{
    
    this.props.content.name}</h4>
            <ul>
                <li>电话:{
    
    this.props.content.number}</li>
            </ul>
        </div>
    )
}

结果
组件的写法有多种,
NameCard组件写法1:

return (
    <div>
        <h4>{this.props.content.name}</h4>
        <ul>
            <li>电话:{this.props.content.number}</li>
        </ul>
    </div>
)

NameCard组件写法2:

return React.createElement('div',{
    
    className: 'shopping-list'},
    React.createElement('h4',),
    React.createElement('ul',null,
        React.createElement('li',null,'hello world')
    ),
);

使用JSX编写的代码都会被转换成使用React.createElement()的形式。

状态提升

思路就是子组件通过调用父组件传递的props事件,并且往里传值,父组件接收子组件传递进来的值,并做统一赋值处理,做到子组件间响应与更新同一值。
下面是案例
App.js

<div className="App">
    <AllInput></AllInput>
</div>

AllInput组件:

import React from 'react';
import Input from './input.js';

class AllInput extends React.Component {
    
    
    constructor(props) {
    
    
        super(props)
        this.state = {
    
     content: '' }
        this.handleContentChange = this.handleContentChange.bind(this)
    }
    
    handleContentChange(newContent) {
    
    
        this.setState({
    
     content: newContent })
    }
    
    render() {
    
    
        return (
            <div>
            	<Input content={
    
     this.state.content } onContentChange={
    
     this.handleContentChange }/>
                <br /><br />
                <Input content={
    
     this.state.content } onContentChange={
    
     this.handleContentChange }/>
            </div>
        )
    }
}

export default AllInput;

Input组件

import React from 'react';

class Input extends React.Component {
    
    
    constructor(props) {
    
    
        super(props)
        this.handleChange = this.handleChange.bind(this)
    }

    handleChange(e) {
    
    
        this.props.onContentChange(e.target.value)
    }

    render() {
    
    
        return (
            <input type='text' value={
    
     this.props.content } onChange={
    
     this.handleChange } />
        )
    }
}

export default Input;

结果

猜你喜欢

转载自blog.csdn.net/weixin_41993525/article/details/114857446