ReactJS - 点击时获得纬度并在输入中显示

Sam*_*nti 1 javascript reactjs redux-form

初学者在这里。我有一个使用地理定位 API 获取纬度和经度的按钮。我在我的控制台上得到了很好的位置,但是我在输入框中显示它们时遇到了问题(以便我可以稍后发布位置信息)。下面是我的组件代码:

export class GetLocation extends Component{
constructor(){
    super();
    this.state = {
        latitude: '',
        longitude: ''
    };
    this.getMyLocation = this.getMyLocation.bind(this);

}

ComponentDidMount(){
    this.getMyLocation();
}
getMyLocation = (e) => {
let location = null;
let latitude = null;
let longitude = null;
if (window.navigator && window.navigator.geolocation) {
    location = window.navigator.geolocation
}
if (location){
    location.getCurrentPosition(function (position) {
        latitude = position.coords.latitude;
        longitude= position.coords.longitude;
        console.log(latitude);
        console.log(longitude);
    })
}
    this.setState({latitude: latitude, longitude: longitude})

}

render(){
    return(
    <div>
        <p>Your location is </p>
        <Field name="latitude" component="input" onChange={this.getMyLocation}/>
        <button type="button" onClick={this.getMyLocation}>Get Geolocation</button>
    </div>

    );
}
}
Run Code Online (Sandbox Code Playgroud)

我正在使用redux-form并且此组件是向导表单的一部分(以防您对Field组件感到疑惑)

mer*_*lin 5

ComponentDidMount应该是componentDidMount。我相信你必须value在你的Field右边设置一个道具?

另外,正如@bennygenel 所提到的,您不需要getMyLocation在构造函数中绑定,因为您已经在使用箭头函数(我在我的示例中使用过,可以随意更改它)。为了访问this.stateinsidegetCurrentPosition的回调,您需要bind成功回调或使用箭头函数。

class App extends React.Component {
  constructor() {
    super()

    this.state = {
      latitude: '',
      longitude: '',
    }

    this.getMyLocation = this.getMyLocation.bind(this)
  }
  
  componentDidMount() {
    this.getMyLocation()
  }

  getMyLocation() {
    const location = window.navigator && window.navigator.geolocation
    
    if (location) {
      location.getCurrentPosition((position) => {
        this.setState({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
        })
      }, (error) => {
        this.setState({ latitude: 'err-latitude', longitude: 'err-longitude' })
      })
    }

  }

  render() {
    const { latitude, longitude } = this.state
    
    return (
      <div>
        <input type="text" value={latitude} />
        <input type="text" value={longitude} />
      </div>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="root"></div>
Run Code Online (Sandbox Code Playgroud)