2017-04-23 30 views
1

我經常發現自己處於需要製作組件的情況下,接受任何有效的HTML屬性以使底層HTML元素使用它們。因爲陣營抱怨不作爲alert屬性input一個有效的正確地避免將無效屬性傳遞給React原語

class Input extends React.Component { 
    // Here I use one of the `props` to add logic to 
    // my component 
    onChange =() => alert(this.props.alert); 

    render() { 
    // Here I want to pass all the properties 
    // down to the HTML input element 
    return <input onChange={this.onChange} {...this.props} /> 
    } 
} 

我上面的示例將拋出一個警告。

我通常解決該問題做如下:

class Input extends React.Component { 
    // Here I use one of the `props` to add logic to 
    // my component 
    onChange =() => alert(this.props.alert); 

    render() { 
    const { 
     alert, // eslint-disable-line no-unused-vars 
     ...props 
    } = this.props; 

    // Here I want to pass all the properties 
    // down to the HTML input element 
    return <input onChange={this.onChange} {...props} /> 
    } 
} 

現在該部件工作正常,但我不覺得舒服的最終結果。

我明白爲什麼React不允許將未知屬性傳遞給它的原語,因爲它們不會使用它們,並且它不會提供無用的屬性,這些屬性將來可能成爲有效的HTML屬性或導致錯誤行爲或副作用。
但我不明白React如何處理這個(很常見的)用例。

有沒有建議的方式來處理這種情況下乾淨的方式?

+0

我看到類似react-css-modules的庫將自己的道具定義爲不可枚舉來解決這個問題,但是我沒有意識到任何使用Rect將props聲明爲不可枚舉的方法。 –

回答

0

除了你的做法,這是主要是我見過做(但我只看到幾家店的風格),浮現在腦海中的另外兩個方法是:

  1. 有單獨提供的常規特性:

    <Input alert={...} general={{className: "foo"}} /> 
    

    然後

    return <input onChange={this.onChange} {...this.props.general} />; 
    

    對此我說:布萊什。繁重的,你用Input,並不構成以及...

  2. 給自己,你可以用它來複制對象留出某些屬性的效用函數,而不是像下劃線/ Lodash的_.omit

    const objectExcept(obj, ...except) { 
        const result = {}; 
        Object.keys(obj).forEach(key => { 
         if (!except.includes(key)) { 
          result[key] = obj[key]; 
         } 
        }); 
        return result; 
    }; 
    

    然後

    return <input onChange={this.onChange} {...objectExcept(this.props, "alert")} />; 
    

    那的objectExcept版採用離散參數,但你可以有它接受一個數組,分隔字符串,無論你的作品...

+0

'objectExcept'是一個解決方案。也許像這樣的問題不太成問題? https://codepen.io/FezVrasta/pen/dWXwBB問題是,兩者都較重,並添加邏輯,可以避免使用我提供的醜陋但快速的解決方法 –

+1

@FezVrasta:這也可以。 (你不需要'delete'。)但是對我來說,這比我們需要的更多的工作。 Re「比較重要」,我不認爲它是,實際上,*除非*你在'render'中使用'alert'。如果你是,你不會有ESLint的事情擔心和解構是正確的選擇。但是在這種情況下,你並沒有使用它,上面的'objectExcept'這個簡單的「給我這個沒有這些屬性的對象」的輸入很少,並且在運行時只有相同的工作量(大致)。 –

-1

也許我誤解了,但爲了排除某些道具,難道你不能只使用解構?

render() { 
    const {foo, bar} = this.props; 
    const inputProps = {foo, bar} 

    return <input onChange={this.onChange} {...inputProps} /> 
    } 

然後你就可以在你的Input類的其他地方使用this.props.alert。

甚至,如果你使用的利差與巴貝爾:

const {alert, ...inputProps} = this.props 

這將從一個新的inputProps對象忽略警報。更多的信息在這裏:clone a js object except for one key

+0

我不想指定哪些屬性應該提供給'input'元素。 –

+0

看我的編輯。如果你使用Babel並傳播運營商,那很簡單 –

+1

這就是我在自己的問題中提供的解決方法...... –