我试图从孩子那里访问父方法以在屏幕上显示模式,但出现错误:This.props.toggleModal is not a function。我将方法传递给孩子,以便可以调用它并使用正确的状态(我认为)。该按钮确实调用了它自己的方法,该方法又调用了父方法。模态组件位于App.js内部。

App.js

class App extends Component {
  constructor() {
  super()
this.state = {
    isOpen: false
 }
}
toggleModal = () => {
this.setState({
  isOpen: !this.state.isOpen
});
console.log('Open');
}
render() {
return (
  <div className="App">
    <Modal toggleModal={this.toggleModal} show={this.state.isOpen}
          onClose={this.toggleModal}>
          Here's some content for the modal
    </Modal>
    <div className="container">
      <Header/>
      <main>
        <Route path="/users"
           children={({ match, ...rest }) => (
             <TransitionGroup component={firstChild}>
               {match && <UserList {...rest} />}
             </TransitionGroup>
        )}/>
        ...
      </main>
      <Footer />
    </div>
  </div>
);
}
}


SearchBar.js-(位于用户页面内)

class SearchBar extends Component {
constructor(props) {
super(props)
this.state = {
  type: this.props.type,
  value: ''
};
}
componentWillReceiveProps(nextProps) {
if (nextProps.type !== this.props.type) {
  this.setState({ type: nextProps.type });
}
};
handleClick = (e) => {
e.preventDefault();
console.log("Clicked!!!");
this.props.toggleModal();
};
handleChange = e => {
  console.log(this.state.type);
  this.setState({ value: e.target.value });
};

render () {
const isUser = this.state.type;
let rightContent = null;
if (isUser === "tour" || isUser === "venue") {
rightContent =
<div className="column">
  <div className="float-right"><button className="add-new" onClick={this.handleClick}>Add New</button></div>
</div>
} else {
rightContent =
<div className="column">
    <div className="float-right">
      <div className="results-block">
        <b>0</b>/<small>292</small>
      </div>
    </div>
  </div>
}
return (
<div className="row main-search">
  <div className="column">
      <form action="">
        <fieldset>
          <label htmlFor="search">
            <input type="text"
                placeholder="Start typing..."
                id="search-box"
                onChange={this.handleChange}
                value={this.state.value} />
          </label>
        </fieldset>
      </form>
  </div>
  {rightContent}
</div>
)
}
}

export default SearchBar;

最佳答案

检查是否在用户页面组件中将toggleModal作为道具。如果是,则将其显式传递给SearchBar

<SearchBar toggleModal = {this.props.toggleModal } /> // plus your rest of the props

10-06 06:17