【问题标题】:React calling methods in different conditionsReact 不同条件下的调用方法
【发布时间】:2018-04-22 21:35:09
【问题描述】:

我是 react 初学者,我已经编写了以下代码:

class Note extends React.Component {
   constructor(props) {
       super(props);
       this.state = {editing: false};

        this.edit = this.edit.bind(this);
        this.save = this.save.bind(this);

   }

   edit() {
       // alert('edit');
       this.setState({editing: !this.state.editing});
   }

   save() {
       this.props.onChange(this.refs.newVal.value, this.props.id);
       this.setState({editing: !this.state.editing});
       // console.log('save is over');
   }

   renderForm() {
       return (
           <div className="note">
               <textarea ref="newVal"></textarea>
               <button onClick={this.save}>SAVE</button>
           </div>
       );
   }

   renderDisplay() {
       return (
           <div className="note">
               <p>{this.props.children}</p>
               <span>
                         <button onClick={this.edit}>EDIT</button>
                        <button onClick={this.remove}>X</button>
               </span>
           </div>
       );
   }

   render() {
       console.log(this.state.editing);
       return (this.state.editing) ? this.renderForm()
           : this.renderDisplay()

   }
}

class Board extends React.Component {

   constructor(props){
       super(props);

       this.state = {
           notes: []
       };

       this.update = this.update.bind(this);
       this.eachNote = this.eachNote.bind(this);
       this.add = this.add.bind(this);
   }

   nextId() {
       this.uniqeId = this.uniqeId || 0;
       return this.uniqeId++;
   }

   add(text) {
       let notes = [
           ...this.state.notes,
           {
               id: this.nextId(),
               note: text
           }
       ];

       this.setState({notes});
   }

   update(newText, id) {
       let notes = this.state.notes.map(
           note => (note.id !== id) ?
               note :
               {
                   id: id,
                   note: newText
               }
       );
       this.setState({notes})
   }

    eachNote(note) {
       return (<Note key={note.id}
                     id={note.id}
                     onChange={this.update}>

           {note.note}
       </Note>)
   }

   render() {
       return (<div className='board'>
           {this.state.notes.map(this.eachNote)}
           <button onClick={() => this.add()}>+</button>
       </div>)
   } 
}

ReactDOM.render(<Board />,
   document.getElementById('root'));

在render()中,onClick事件有一个函数,即如果这样使用:{this.add}会产生如下错误:

未捕获的错误:对象作为 React 子对象无效(找到:具有键 {dispatchConfig、_targetInst、nativeEvent、type、target、currentTarget、eventPhase、bubbles、cancelable、timeStamp、defaultPrevented、isTrusted、view、detail 的对象。 ..})

为什么?而在 eachNote() 方法中使用了这个命令:

onChange={this.update}

并且没有错误。

谁能告诉我原因?谢谢。

【问题讨论】:

    标签: javascript reactjs methods


    【解决方案1】:

    问题在于,在 add 函数中,您正在获取参数文本并将其设置为状态,因此当您调用 onClick={() =&gt; this.add()} 时,您没有将任何参数传递给 add 函数,因此在其定义中 text 未定义因此state note 被设置为未定义。

    但是,如果您像 onClick={this.add} 一样直接调用它,add 函数会接收 event 对象作为参数,因此它将 state note 设置为您用于 render 的事件对象

    【讨论】:

    • 如何使用这个:onClick={this.add}。我应该做出哪些改变?
    • 如果您想将文本值传递给 add 函数,那么 onClick={this.add} 将无法直接工作。您还需要将值绑定到函数,以便您可以执行 onClick={this.add.bind(this, text)}onClick={() =&gt; this.add(text)}
    【解决方案2】:

    onClick={this.add} 会将点击事件传递给this.add

    所以你需要做的是:

    onClick={e =&gt; this.add('some text')} 或类似名称。

    如果你想onClick={this.add},你必须确保你的添加方法是:add(event) { ... }

    【讨论】:

    • 我编辑了我的代码并在 Note 类中添加了 save() 方法,在 renderForm() 方法中我使用了 onClick={this.save} 并且没有错误但在 Board 类中render 方法这是个问题。
    【解决方案3】:

    &lt;Note /&gt; 组件不包含用于返回任何内容的render() 方法。添加一个render() 方法并返回一些东西。

    class Note extends React.Component {
       constructor(props) {
           super(props);
           this.state = {editing: false};
    
            this.edit = this.edit.bind(this);
    
       }
    
       edit() {
           // alert('edit');
           this.setState({editing: !this.state.editing});
       }
       
       render() {
         return (
           <div>Render something</div>
         )
       }
    }
    
    class Board extends React.Component {
    
       constructor(props){
           super(props);
    
           this.state = {
               notes: []
           };
    
           this.update = this.update.bind(this);
           this.eachNote = this.eachNote.bind(this);
           this.add = this.add.bind(this);
       }
    
       nextId() {
           this.uniqeId = this.uniqeId || 0;
           return this.uniqeId++;
       }
    
       add(text) {
           let notes = [
               ...this.state.notes,
               {
                   id: this.nextId(),
                   note: text
               }
           ];
    
           this.setState({notes});
       }
    
       update(newText, id) {
           let notes = this.state.notes.map(
               note => (note.id !== id) ?
                   note :
                   {
                       id: id,
                       note: newText
                   }
           );
           this.setState({notes})
       }
    
        eachNote(note) {
           return (<Note key={note.id}
                         id={note.id}
                         onChange={this.update}>
    
               {note.note}
           </Note>)
       }
    
       render() {
           return (<div className='board'>
               {this.state.notes.map(this.eachNote)}
               <button onClick={() => this.add()}>+</button>
           </div>)
       } 
    }
    
    ReactDOM.render(<Board />,
       document.getElementById('root'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>
    
    <div id="root"></div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-17
      • 1970-01-01
      • 2015-06-13
      • 1970-01-01
      相关资源
      最近更新 更多