Home > Web Front-end > JS Tutorial > What are the ways to pass parameters in react?

What are the ways to pass parameters in react?

王林
Release: 2021-02-02 11:41:30
forward
2020 people have browsed it

What are the ways to pass parameters in react?

React is a JAVASCRIPT library for building user interfaces.

React is mainly used to build UI. Many people think that React is the V (view) in MVC.

React originated as an internal project at Facebook to build the Instagram website and was open sourced in May 2013.

React has high performance and very simple code logic. More and more people have begun to pay attention to and use it.

The most common thing is to pass parameters between parent and child components

The parent component passes the value to the child component, which can be realized directly by using this.props

In the parent component, give the needs Add a custom attribute to the subcomponent that passes data. You can get the data passed by the parent component through this.props in the subcomponent.

// 父组件 render() {        
    return (                // 使用自定义属性传递需要传递的方法或者参数
                <ShopUi toson={this.state}></ShopUi>            
                   )
    } 

//子组件 //通过this.props.toson就可以获取到父组件传递过来的数据 、、如果还需要往孙组件传递那么在子组件通过自定义属性继续传递就行了
      tograndson={this.props.toson}
、、孙组件通过this.props.tograndson获取到数据
Copy after login

If the subcomponent passes a value to the parent component, it needs to be set in the parent component. Receive function and state, and pass the function name to the subcomponent through props

That is, the method of passing the parent component to the subcomponent, and calling it in the subcomponent

//孙子组件export default class Grandson extends Component{
    render(){        return (            <div style={{border: "1px solid red",margin: "10px"}}>
        {this.props.name}:                <select onChange={this.props.handleSelect}>
                    <option value="男">男</option>
                    <option value="女">女</option>
                </select>
            </div>        )
    }
}; 
//子组件export default class Child extends Component{
    render(){        return (            <div style={{border: "1px solid green",margin: "10px"}}>
                {this.props.name}:<input onChange={this.props.handleVal}/>
                <Grandson name="性别" handleSelect={this.props.handleSelect}/>
            </div>        )
    }
}; 
//父组件export default class Parent extends Component{
 
    constructor(props){
        super(props)        this.state={
            username: &#39;&#39;,
            sex: &#39;&#39;
        }   
    },
    handleVal(event){        this.setState({username: event.target.value});
    },
    handleSelect(value) {        this.setState({sex: event.target.value});
    },
    render(){        return (            <div style={{border: "1px solid #000",padding: "10px"}}>
                <div>用户姓名:{this.state.username}</div>
                <div>用户性别:{this.state.sex}</div>
                <Child name="姓名" handleVal={this.handleVal} handleSelect={this.handleSelect}/>
            </div>        )
    }
}
Copy after login

Someone asked some time ago I have a question, what is super() in the constructor used for?

To summarize:

If you want to use this in the constructor of the subclass, you must call the parent class constructor, otherwise you will not get this

Then the problem arises, How to call the constructor of the parent class? Through super()

If you want to use the parameters passed by the parent component in the constructor, you must pass the parameters to the parent component's constructor when calling super.

If you do not use this in the constructor , or parameters, there is no need for super; because React has done this for you, the binding of props

Routing parameters

Install npm install react-router-dom --save-dev

Define the route (usually placed outside)

 <HashRouter> 
    <Switch> 
        <Route exact path="/" component={Home}/> 
        <Route exact path="/detail" component={Detail}/> 
    </Switch> 
</HashRouter>
Copy after login

When the page jumps

<li  onClick={el => this.props.history.push({
   pathname:&#39;/detail&#39;,
      state:{id:3}
})}>
</li>
Copy after login

Receive the passed data through this.props.history.location

Routing parameters may have this problem, that is, only the component mounted when the route is defined will have the location history match in props

The component mounted on the route is generally It is Container.js. Generally, we will separate out the UI.js component and click to jump here. There is no location history match in the UI component props

You need to use the high-order component withRouter

State promotion

Promote the state that multiple components need to share to the public parent component closest to them, and then the parent component distributes it to the child component through props

context

When a component saves a certain state in its own context, all descendant components under the component can access this state without the need for the transfer of intermediate components, and the parent component of this component cannot access it.

class Index extends Component {
  static childContextTypes = {
    themeColor: PropTypes.string
  }

  constructor () {
    super()
    this.state = { themeColor: &#39;red&#39; }
  }

  getChildContext () {
    return { themeColor: this.state.themeColor }
  }

  render () {
    return (
      <div>
        <Header />
        <Main />
      </div>
    )
  }
}
通过getChildContext()将属性传递给所有的子孙组件
提供 context 的组件必须提供 childContextTypes 作为 context 的声明和验证。
Copy after login
class Title extends Component {
  static contextTypes = {
    themeColor: PropTypes.string
  }

  render () {
    return (
      <h1 style={{ color: this.context.themeColor }}>标题</h1>
    )
  }
}
子组件要获取 context 里面的内容的话,就必须写 contextTypes 来声明和验证你需要获取的状态的类型,它也是必写的,如果你不写就无法获取 context 里面的状态。
Title 想获取 themeColor,它是一个字符串,我们就在 contextTypes 里面进行声明。
Copy after login

Introducing redux

redux provides a predictable state management mechanism for React

redux stores the entire application state in the store, which stores a state tree

Components can dispatch (dispatch) behaviors (actions) to the store instead of directly notifying other components

Other components can refresh their own views by subscribing to the state in the store

Related recommendations: react tutorial

The above is the detailed content of What are the ways to pass parameters in react?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template