ReactJS - 将内联样式设置为等于状态上的属性不起作用。这是怎么回事?



我正在尝试在用户输入不正确的信息时获得一个formwarning,但似乎已经消失在我身上。我正在尝试控制它是否使用this.state.formwarning.display显示 - 当validateInputs函数运行时,如果确定输入是无效的,则应将显示值从'none''更改为'block'。我正在尝试为组件设置样式,以使其具有与this.state.state.formwarning.display匹配的显示,但是我遇到了一个错误。我的信念是您可以通过不正确的对象设置组件内联的样式吗?无论如何都会得到虫子。IE

export default class FormOne extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      formOne: {
        shippingAddress: {
          firstName: '',
          lastName: '',
          address1: '',
          city: '',
          state: '',
          zip: '',
          country: 'US'
        },
        phone: '',
        email: ''
      },
      formWarning: {
        text: '',
        invalidInputID: '',
        display: 'block'
      },
      isSubmitted: false,
      submitting: false
    }
    this.styles = this.props.styles || {}
  }
  componentWillReceiveProps(nextProps) {
    if(nextProps.state.stepOne && 
nextProps.state.stepOne.formOneResponse) {
  let formOneResponse = nextProps.state.stepOne.formOneResponse
  formOneResponse.status === "delayed" || formOneResponse.status === "success"
    ? this.setState({isSubmitted: true})
    : alert(formOneResponse.errorMessage)
  this.setState(state => ({submitting: false}))
}
 }

validateInputs = (inputs) => {
  let { email, phone, shippingAddress } = inputs,
    shippingKeys = Object.keys(shippingAddress)
    console.log('validate inputs is firing')
    for(let i = 0; i < Object.keys(shippingAddress).length; i++) {
      let key = shippingKeys[i], input = shippingAddress[key]
      if(!input) {
        return this.showFormWarning(key)
    }
  }
    if(!phone) return this.showFormWarning('phone')
    if(/S+@S+.S+/.test(email)) return 
this.showFormWarning('email')
    return true
  }
  showFormWarning = key => {
    clearTimeout(this.warningTimeout)
     console.log('showformwarnign is firing')
    this.setState(state => ({
      formWarning: {
        ...state.formWarning,
        text: 'Please fill out this field',
        invalidInputID: key,
        display: 'block'
      }
    }))
    this.warningTimeout = setTimeout(() => {
      this.setState(state => ({
        formWarning: {
          ...state.formWarning,
          display: 'none'
        }
      }))
    }, 5000)
    return false
  }
  saveInputVal = (event) => {
    let { formOne: tempFormOne } = this.state,
        input = event.currentTarget
      console.log('saveinputvals is firing')
     if(input.name === 'phone' || input.name === 'email') {
      this.setState(state => ({
        formOne: {
          ...state.formOne,
          [input.name]: input.value
        }
      }))
    } else {
      this.setState(state => ({
        formOne: {
          ...state.formOne,
          shippingAddress: {
           ...state.formOne.shippingAddress,
            [input.name]: input.value
          }
        }
      }))
    }
  }
  submit = (event) => {
    event.preventDefault()
    if(!this.validateInputs(this.state.formOne)) return
    this.setState(state => ({submitting: true}))
    this.props.saveShippingData(this.state.formOne)
    this.props.stepOneSubmit(this.state.formOne)
  }
  render() {
    if (this.state.isSubmitted) return <Redirect to="/order" />
    let CustomTag = this.props.labels ? 'label' : 'span',
        { inputs, saveInputVal, styles, state } = this,
        { formWarning, submitting } = state,
        { invalidInputID, text, display } = formWarning
     return (
      <div style={this.styles.formWrapper}>
        {
          typeof this.props.headerText === 'string'
            ? ( <h2 style={this.styles.formHeader}>
{this.props.headerText}</h2> )
            : this.props.headerText.map((text) => {
              return <h2 key={text} style={this.styles.formHeader} 
className={'header'+this.props.headerText.indexOf(text)}>{text}</h2>
            })
        }
        <form onSubmit={this.submit} style={this.styles.form}>
          <FormOneInputs inputs={inputs} saveInputVal={saveInputVal} 
CustomTag={CustomTag} styles={styles} />
          <button style={this.styles.button}>{this.props.buttonText}
</button>
        </form>
        <Throbber throbberText='Reserving your order...' showThrobber=
{submitting} />
        <FormWarning style={display: {this.state.formWarning.display}} invalidInputID={invalidInputID} text={text}/>
      </div>
    )
  }
}

您不需要设置任何CSS类。该方法如下:

(1(给定您要渲染或不呈现的组件,具体取决于变量

(2(制作一种辅助方法,该方法检查条件并在渲染的情况下返回实际组件。否则,什么都不做(基本上返回未定义(

(3(从您希望零件出现的任何地方调用该方法。

具体示例:

class FormOne extends React.Component {
  // (...) all other things omitted to focus on the problem at hand
  renderFormWarning() {
    if (formIsInvalid) {
      return <FormWarning ... />;
    }
    // else won't do anything (won't show)
  }
  render() {
    return (
      {/* ... */}
      {this.renderFormWarning()}
    );
  }
}

在上面的示例中,用一些语句替换formIsInvalid,这些语句会告诉您表格是否无效。然后,如果该条件为真,它将返回FormWarning组件。否则,不会显示任何表格警告。从render()方法中,您需要做的就是调用该辅助方法。

最新更新