NooNoo
@NooNoo
Yep

Как воспользоваться функцией, переданной в props?

Всем привет!

Выводит ошибку: _this.props.onNodeAdd is not a function.
В чем ошибка?

Родительский компонент:
export default class App extends Component {
  render() {
    return(
        <div className="app">
          <h2 className="app__header">Notes</h2>
          <NoteEditor onNoteAdd = {this.handleNoteAdd.bind(this)}/>
          <NotesGrid />
        </div>
    )
  }

  handleNoteAdd = (data) => {
    console.log('I need this --->', data);
  };
}


Дочерний компонент:
export default class NoteEditor extends Component {
  state = {
    title: '',
    text: '',
    color: '#ffffff'
  };

  render() {
    return (
        <div className='note-editor'>
          <input
              type='text'
              className='note-editor__title'
              placeholder='Enter title'
              value = {this.state.title}
              onChange = {this.handleTitleChange}
          />
          <textarea
              placeholder='Enter note text'
              rows = {5}
              className='note-editor__text'
              value = {this.state.text}
              onChange = {this.handleTextChange}
          />
          <div className='note-editor__footer'>
            {/*<ColorPicker*/}
                {/*value={this.state.color}*/}
                {/*onChange={this.handleColorChange}*/}
            {/*/>*/}
            <button
                className='note-editor__button'
                disabled = {!this.state.text}
                onClick = {this.handleNoteAdd}
            >
              Add
            </button>
          </div>
        </div>
    )
  }

  handleTitleChange = (evt) => {
    this.setState({
      title: evt.target.value
    });

  };

  handleTextChange = (evt) => {
    this.setState({
      text: evt.target.value
    });
  };

  handleNoteAdd = () => {
    const newNote = {
      title: this.state.title,
      text: this.state.text,
      color: this.state.color
    };

    this.props.onNodeAdd(newNote);
    // console.log('---', newNote);

    this.setState({
      title: '',
      text: '',
      color: '#ffffff'
    });
  }
}
  • Вопрос задан
  • 65 просмотров
Решения вопроса 2
0xD34F
@0xD34F Куратор тега React
onNoteAdd = {this.handleNoteAdd.bind(this)}

this.props.onNodeAdd(newNote)

Так как всё-таки правильно - Note или Node? Вы уж разберитесь.

UPD. А что так многословно?

Можно и покороче, вместо

const newNote = {
  title: this.state.title,
  text: this.state.text,
  color: this.state.color
};

this.props.onNodeAdd(newNote);

пусть будет this.props.onNoteAdd({ ...this.state });.

Также нет необходимости в двух методах для обновления стейта, можно сделать общий, а какое свойство должно быть обновлено - указывать через атрибут name:

onChange = ({ target: { name, value } }) => {
  this.setState({ [name]: value });
}

<input
  name="title"
  onChange={this.onChange}
  ...
/>
<textarea
  name="text"
  onChange={this.onChange}
  ...
/>

Ответ написан
@ParaBellum577
onNoteAdd = {this.handleNoteAdd.bind(this)}/>

this.props.onNodeAdd(newNote);

Прочти внимательно и сам поймешь
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы