简体   繁体   English

如何在不渲染组件的情况下传递道具?

[英]How to pass props without rendering the component?

I have two components one called ReturningCustomer and the other one called Update . 我有两个组件,一个名为ReturningCustomer ,另一个名为Update I have a phone number saved in state in ReturningCustomer and I want to pass that phone number to the Update component with having to render Update or use Redux: 我在ReturningCustomer中保存了状态的电话号码,我想将该电话号码传递给更新组件,而不必渲染更新或使用Redux:

render() {
       return (
        <div className="row returning-customer">
            <h3>Returning Customer</h3>
            <div className="col">
                <p className="error">{this.state.error}</p>
                <form className="row" onSubmit={this.onSubmit}>
                    <label>Phone Number</label>
                    <input 
                        type="text"
                        className="validate"
                        onChange={this.onPhoneNumberChange}
                    />
                    <button className="btn">Go</button>
                </form>
            </div>
            <Update 
                phoneNumber={this.state.phoneNumber} 
            />
        </div>
    );

} }

It's not entirely clear what you're asking based on the current description, but it sounds like you're either wanting to conditionally render a component while passing props, or you want to know how to use those props? 根据当前的描述,你所要求的并不完全清楚,但听起来你想要在传递道具时有条件地渲染组件,或者你想知道如何使用这些道具? I'm including both here. 我在这里包括两个。

Conditionally rendering a component and passing props: 有条件地渲染组件并传递道具:

// SomeComponent.js

import React from 'react'
import Update from '../..'

class SomeComponent extends React.Component {
  state = { phoneNumber: '' };

  renderUpdate() {
    const someCondition = true;

    if (someCondition) {
      return <Update phoneNumber={this.state.phoneNumber} />
    }

    return null
  }

  render() {
    return (
      <div>
        {this.renderUpdate()}
      </div>
    )
  }
}

export default SomeComponent

Using props: 使用道具:

// Update.js

import React from 'react'

// destructuring the props object here
const Update = ({ phoneNumber }) => (
   <div>
     <p>{phoneNumber}</p>
   </div>
)

export default Update

In the render function for Update you could use either one of the following and the component would not render 在Update的渲染函数中,您可以使用以下任一项,并且组件不会呈现

render() { 
   return false; 
}

render() { 
   return null; 
}

render() { 
   return []; 
}

render() { 
   return <></>; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM