2017-10-17 31 views
1

我有這個組件:JSX打印文本有條件的財產沒有風格的分量值

<Button type="submit" { invalid ? 'primary': null }> 

此組件樣式的組件:

import styled from 'styled-components'; 

export const Button = styled.button` 
    font-size: 15px; 
    padding: 0.25em 1em; 
    border: solid 1px ${(props) => { 
     let color; 
     if (props.primary) { 
     color = 'red'; 
     } else { 
     color = '#ffffff'; 
     } 
     return color; 
    }}; 
    `; 

我得到這個錯誤:

Syntax error: Unexpected token ^invalid, expected ... (64:54)

我只需要發送屬性'主'如果無效是真實的,得到這個:

<Button type="submit" primary/> 

我不想寫:

primary = { invalid } 

的組件調用這個按鈕是:

import React from 'react'; 
import { Button } from './layouts/cssstyled'; 
const getConditionalProps = (props) => { 
    // fill your `invalid` variable in this function or pass it to it 
    const myprops = {}; 
    myprops.primary = true ; 
    myprops.secondary = false; 
    return myprops; 
} 

const Form = (props) => { 
    console.log('form props'); 
    console.log(props); 

    const { handleSubmit, invalid, pristine, reset, submitting, t } = props; 
    return (
    <form onSubmit={handleSubmit}> 
     <p>Invalid? {JSON.stringify(invalid)}</p> 

     <Button type="submit" disabled={submitting} primary={invalid ? "" : null} > 
      Buton styled component does not work 
     </Button> 
     <button primary={invalid ? "" : null}> button native works</button> 

     <div className="formError"> 
      {pristine} 
      {invalid && t('form.haserrors')} 
     </div> 

     </div> 

    </form> 
); 
}; 

export default reduxForm({ 
    form: 'CustomerForm', // a unique identifier for this form 
})(Form); 
+1

正確的方法肯定會讓你寫'primary = {invalid}'。有什麼理由不寫嗎? – ZekeDroid

+0

我使用一個只需要'主要'的CSS庫,但爲什麼我不能在jsx中打印文本的技術原因? – DDave

+0

@Dave由於react不是一個打印庫,它是一個呈現爲HTML的虛擬DOM。 – Sulthan

回答

0

您可以使用布爾值,讓你的條件會變成這個樣子:

<Button type="submit" primary={ !!invalid } > 

或者如果你不想讓你的按鈕在假時有一個主要的值,你可以這樣做:

const button = invalid ? <Button type="submit" primary > : <Button type="submit" > 
+1

但我需要

+0

明白了,我更新了我的答案。 – Shota

+0

我的意思是,如果無效是錯誤的,我不想顯示'主要',在你的例子中主要是打印,或者不可能? – DDave

0

我建議使用React-JS Spread Attributes。這是偉大的工具來傳播與條件行爲的組件上的道具:

class MyComponent extends React.Component { 
    // ... 

    getConditionalProps() { 
     const props = {}; 
     // fill your `invalid` variable in this function or pass it to it 
     if (invalid) { 
      props.primary = true; 
     } 
     return props 
    } 

    render() { 
     return (
      <Button type="submit" 
        { ...this.getConditionalProps() } /> 
     ); 
    } 
} 

另一種解決方案是有條件的渲染:

class MyComponent extends React.Component { 
    // ... 

    render() { 
     return (invalid ? 
      <Button type="submit" primary /> 
      : 
      <Button type="submit" /> 
     ); 
    } 
} 

請注意,有可能是一個更好的解決您的問題:你需要從組件本身內部處理組件Button的行爲,而不是試圖從父組件決定是否發送特定的道具。但上述解決方案完全符合您的要求。

+0

謝謝,我可以得到這個

+0

我已經更新了將'true'放入'primary' prop的答案,這相當於寫作:'

+0

謝謝,但是你的解決方案不適用於boolean值,不打印屬性,只是當道具有字符串值時 – DDave