首页 > 解决方案 > “this.props”在哪里定义?

问题描述

任何帮助或提示将不胜感激。在 SearchBar.js 中,“this.props”是在哪里定义的?我没有看到 SearchBar.js 类中定义了这个变量?

是因为 React.Component 类吗?在谷歌浏览器中调试时如何进入这个 React.Component 类?

搜索栏.js:

                import React from 'react';

            class SearchBar extends React.Component {

               state = { term: '' };


               onFormSubmit = event => {
                event.preventDefault();
                this.props.onSubmit(this.state.term);
                console.log(this.state.term);
               }


                render() {
                return (
                <div className="ui segment">
                    <form onSubmit={this.onFormSubmit} className="ui form">
                    <div className="field">
                        <label>Image Search</label>
                        <input type="text" value={this.state.term} onChange={(e) => this.setState({ term: e.target.value.toUpperCase()})} />
                    </div>
                    </form>

                </div>);
                }
            }

应用程序.js:

            import React from 'react';
        import SearchBar from './SearchBar';

        class App extends React.Component {

            onSearchSubmit(term) {
            console.log(term);
            }
            render() {
            return (
                <div className="ui container" style={{ marginTop: '10px'}}>
                <SearchBar onSubmit={this.onSearchSubmit} />
                </div>
                );
            }

        }

        export default App;




            export default SearchBar;

标签: reactjs

解决方案


超类在实例上React.Component创建一个props对象,并将传递给实例的任何道具分配给它。如果你去react.development.js(或ReactBaseClasses.js),你会看到:

function Component(props, context, updater) {
  this.props = props;

其中第一个参数 ,props将包含调用组件的道具。

在这里,由于组件是这样调用的:

<SearchBar onSubmit={this.onSearchSubmit} />

它有一个道具,onSubmit,所以道具是:

{
  onSubmit: this.onSearchSubmit
}

推荐阅读