【问题标题】:Best method to combine defined props in React component在 React 组件中组合已定义道具的最佳方法
【发布时间】:2020-06-29 05:50:53
【问题描述】:

我有一个组件可以接收first_namelast_name 等用户详细信息的道具。 first_namelast_name 之一可能是 undefined 或两者都是 undefined

我想在父组件中接收它并通过这样的组合来显示它:

contactName = {props.client_firstname || props.client_lastname ?
           props.client_firstname +" " +props.client_lastname : "N/A" }

检查是否在上述三元条件内为first_namelast_name 设置了值并仅组合定义的值的最佳方法是什么?

【问题讨论】:

    标签: javascript reactjs string-concatenation react-props conditional-operator


    【解决方案1】:

    您可以设置默认的道具类型

    YoursComponent.defaultProps = {
      client_firstname: '',
      client_lastname: ''
    };
    
    contactName={props.client_firstname +" " +props.client_lastname }
    

    不需要三元运算符。如果它未定义,那么它将从默认道具中获取默认值。

    谢谢

    【讨论】:

    • 如果 first 未定义,则拼接结果将是 `x`(以空白开头)
    • 我理解你的问题。我只是从反应的角度给出一个方向。如果他认为这是正确的方法,那么他可以增强这种逻辑。 :)
    • @QubaishBhatti 有没有帖子解决了你的问题?如果您还有其他问题,请告诉我们。
    【解决方案2】:

    试试这个。

    contactName = {
                    ([props.client_firstname, props.client_lastname])
                    .join(" ")
                    .trim()
                  }
    

    例子:

    console.log(["FirstName", undefined].join(" ").trim());
    
    console.log([null, "LastName"].join(" ").trim());
    
    console.log(["FirstName", "LastName"].join(" ").trim());
    
    console.log([null, undefined].join(" ").trim());

    【讨论】:

      【解决方案3】:

      function getFullName( props = {} ){
        const{ client_firstname='', client_lastname='' } = props;
      
        let SEPERATOR = client_firstname && client_lastname ? " ": "";
        
        return `${client_firstname}${SEPERATOR}${client_lastname}`
      }
      
      console.log( getFullName(
       { client_firstname:'stack', client_lastname:'overflow' }
      ))
      
      console.log( getFullName(
       { client_firstname:'', client_lastname:'overflow' }
      ))
      
      console.log( getFullName(
       { client_lastname:'overflow' }
      ))
      
      console.log(getFullName(
       { client_firstname:'stack', client_lastname:undefined}
      ))
      
      console.log(getFullName(
        {}
      ))
      console.log(getFullName())

      【讨论】:

        【解决方案4】:

        你可以使用一个数组来存储这两个props,

        然后join()trim(),最后为N/A添加conditional operator

        const generator = list => {
          const result = list.join(" ").trim();
          return result ? result : "N/A";
        };
        
        console.log('>' + generator(["first", "second"]) + '<');
        console.log('>' + generator(["first", undefined]) + '<');
        console.log('>' + generator([undefined, "second"]) + '<');
        console.log('>' + generator([undefined, undefined]) + '<');

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-04-17
          • 2020-11-27
          • 2020-03-10
          • 2021-05-02
          • 2020-06-30
          • 2015-06-15
          • 2019-08-29
          相关资源
          最近更新 更多