2017-08-26 63 views
0

好像有很多這樣的錯誤的方法和我相當肯定,我想這樣做的錯誤的方式(請注意這個代碼不目前的工作):在React + Redux中將參數傳遞給reducer的正確方法?

class SubmitLink extends React.Component<SubmitLinkProps, {}>{ 
    constructor(props: SubmitLinkProps) { 
     super(props); 

     this.urlToPass = "nothing"; 
    } 

    urlToPass: string; 
    handleChange(e: React.FormEvent<HTMLInputElement>) { 
     this.urlToPass = e.currentTarget.value; 
    } 

    public render() { 
     return <div> 
      <div>hello world {this.props.url}</div> 
      <input onChange={this.handleChange} type='text'></input> 
      <button onClick={() => { 
       this.props.submitlink(this.urlToPass); 
      }}>submit</button> 
     </div> 
    } 
} 

除了事實代碼不起作用(urlToPass在運行時未定義,不確定原因)我只是爲了從文本字段獲取輸入而看起來像一大堆工作。同時,這是我可以找到如何做到這一點的唯一方法,但它確實感覺不對。

回答

2

這裏的問題是元素包含它自己的狀態,而React組件也有它們自己的內部狀態。處理這個問題的最好方法是使React組件成爲真相的來源。你可以閱讀更多關於這個最佳實踐這裏:https://facebook.github.io/react/docs/forms.html

在你的情況,這將是做到以下幾點:

class SubmitLink extends React.Component<SubmitLinkProps, {}>{ 
    constructor(props: SubmitLinkProps) { 
     super(props); 

     this.state = { urlToPass: '' } 
     this.handleChange = this.handleChange.bind(this) 
    } 

    handleChange(e: React.FormEvent<HTMLInputElement>) { 
     this.setState({urlToPass: e.currentTarget.value}); 
    } 

    public render() { 
     return <div> 
      <div>hello world {this.props.url}</div> 
      <input value={this.state.urlToPass} onChange={this.handleChange} type='text'></input> 
      <button onClick={() => { 
       this.props.submitlink(this.state.urlToPass); 
      }}>submit</button> 
     </div> 
    } 
} 
+1

另外值得一提的是,使用ES6語法自動綁定「這個」到功能:myFunction的= (params)=> {code}; – Adam

+0

好叫出亞當! – TheBottleSeller

+0

嗯試着這個代碼我得到這個錯誤:TS2339:'只讀<{}>'類型不存在屬性'urlToPass'。 – tweetypi

1

你應該在你的構造函數中綁定handleChange方法。 this.handleChange = this.handleChange.bind(this);

相關問題