2017-06-22 32 views
1

我正在嘗試使用多年呈現選擇下拉菜單。Javascript函數未在表單中呈現

我使用一個簡單的循環來生成下拉菜單的所有年份,請參閱dateYear()

如果我把{this.dateYear()}放在{this.state.careerHistoryPositions.map((careerHistoryPosition)之外,但是當我把它放在{this.state.careerHistoryPositions.map((careerHistoryPosition)裏時,它呈現正確,但是它呈現select元素,但是不填充年份。

我在控制檯中沒有收到任何錯誤。

export default class CareerHistoryFormPage extends Component { 
    constructor(props) { 
    super(props); 

    const profileCandidateCollection = props.profileCandidate; 
    const careerHistoryPositions = profileCandidateCollection && profileCandidateCollection.careerHistoryPositions; 

    this.state = { 
     careerHistoryPositions: [{company: '', startDateYear: ''}], 
    }; 
    } 

    dateYear() { 
    var yearDate = ''; 
    for (var i = new Date().getFullYear(); i >= 1975; i--) { 
     yearDate += '<option value="' + i + '">' + i + '</option>'; 
    } 
    $('select').html('<option>Year</option>' + yearDate); 
    } 
} 
render() { 
    return (
    <form onSubmit={this.handleFormSubmit}> 
     {this.state.careerHistoryPositions.map((careerHistoryPosition) => (

     <div key={careerHistoryPosition.uniqueId}> 
      <input 
      type="text" 
      value={careerHistoryPosition.company} 
      onChange={this.handleCompanyNameChange(careerHistoryPosition.uniqueId)} 
      /> 

      <select value={CareerHistoryFormPage.startDateYear} > 
      {this.dateYear()} 
      </select> 

     </div> 
     </form> 
    ); 
    } 
} 
+0

該建議是怎麼回事? – bp123

回答

0

我不認爲這是最優雅的解決方案,但是,這是我得到它的工作。問題是jQuery。感謝@ nem035指出了這一點。

export default class CareerHistoryFormPage extends Component { 
    constructor(props) { 
    super(props); 

    const profileCandidateCollection = props.profileCandidate; 
    const careerHistoryPositions = profileCandidateCollection && profileCandidateCollection.careerHistoryPositions; 

    this.state = { 
     careerHistoryPositions: [{company: '', startDateYear: ''}], 
    }; 
    } 

    getStartDateMonthSelect(careerHistoryPosition) { 
    const monthRange = []; 
    for (let i = 0; i <= 11; i++) { 
     monthRange.push(i); 
    } 
    return (
     <select value={careerHistoryPosition.startDateMonth} onChange={this.handleStartDateMonthChange(careerHistoryPosition.uniqueId)}> 
     <option>Month</option> 
     {monthRange.map(month => (
      <option key={month} value={month}>{moment().month(month).format('MMMM')}</option> 
     ))} 
     </select> 
    ); 
    } 
} 
render() { 
    return (
    <form onSubmit={this.handleFormSubmit}> 
     {this.state.careerHistoryPositions.map((careerHistoryPosition) => (

     <div key={careerHistoryPosition.uniqueId}> 
      <input 
      type="text" 
      value={careerHistoryPosition.company} 
      onChange={this.handleCompanyNameChange(careerHistoryPosition.uniqueId)} 
      /> 

      {this.getStartDateMonthSelect(careerHistoryPosition)} 

     </div> 
     </form> 
    ); 
    } 
}