2017-08-26 278 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);