【问题标题】:Why react native props not works?为什么反应原生道具不起作用?
【发布时间】:2021-07-05 08:09:29
【问题描述】:

您能帮我解决以下问题吗:

props.title 没有出现在 {props.title} 中

console.log(props.title); //返回Mobile App,那么console中有几行未定义?

console output

我正在使用 react native+typescript。

import React  from 'react';
import ReactDOM from 'react-dom';

const MobileApp = (props : any)  => {
    console.log(props.title);
    return (
        <div >
        <div>Test</div>
        <div>{props.title}</div>
        </div >
    );
  
}

ReactDOM.render(
    <MobileApp title="Mobile App"/>,
  document.getElementById('root')
);

export default MobileApp;

【问题讨论】:

  • 你怎么知道它在渲染中是未定义的?也许您缺少一些样式以确保它出现在页面上?

标签: typescript react-native


【解决方案1】:
Finally found solution. Code was divided in 2 files. App.tsx:
-------------------------------------------------------------
import MobileApp from './MobileApp';
import React from 'react';
import ReactDOM from 'react-dom';

const App = () => {
  return ReactDOM.render(
    <MobileApp title="Mobile App"/>,
    document.getElementById('root')
  );
}

export default App;
-------------------------------------------------------------
and MobileApp.tsx:
-------------------------------------------------------------
export interface MobileApp {
  title: string;
}

const MobileApp = (props: MobileApp)  => {
    console.log(props.title);
    return ( 
        <div >
        <div>{props.title}</div>
        <Form />
        </div >
    );
}

class Form extends React.Component {
    state = { userName: '', password: '' };
    handleSubmit = (event : any) => {
    event.preventDefault();
    console.log(this.state.userName + ' ' + this.state.password );
  };
    render() {
    return (
        <form onSubmit={this.handleSubmit}>
            <input 
            type="text" 
            value={this.state.userName} 
            onChange={event => this.setState({ userName: event.target.value })}
            placeholder="Username"/><br/>
            <input 
            type="text" 
            value={this.state.password} 
            onChange={event => this.setState({ password: event.target.value })}
            placeholder="Password"/><br/>
        <button>Login</button>
        </form>
    );
  }
}

export default MobileApp;

【讨论】:

    【解决方案2】:

    这样使用

    const MobileApp = props  => {
    

    const MobileApp = ({props})  => {
    

    【讨论】:

    • 它与问题中的写法有何不同?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 2021-02-27
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 2021-10-26
    相关资源
    最近更新 更多