前几天我有人教我如何使用以下内容创建组件:
HelloWorld.js
import React from 'react';
export default function HelloWorld(props) {
return (
<p>
Hello, world!
</p>
);
}
与我在其他地方找到的相比,我非常喜欢它。我的问题是,我没有看到太多,如果有的话,在那里做类似的事情。我想将下面的内容转换成上面的内容,但我不确定如何这样做:
UserGist.js
import React from 'react';
import ReactDOM from 'react-dom';
import * as $ from 'jquery';
var UserGist = React.createClass({
getInitialState: function() {
return {
username: '',
name: '',
company: '',
location: '',
email: ''
};
},
componentDidMount: function() {
this.serverRequest = $.get(this.props.source, function (result) {
this.setState({
username: result.login,
name: result.name,
company: result.company,
location: result.location,
email: result.email
});
}.bind(this));
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
return (
<div>
<ul>
<li><b>Username:</b> {this.state.username}</li>
<li><b>Name:</b> {this.state.name}</li>
<li><b>Comapny:</b> {this.state.company}</li>
<li><b>Location:</b> {this.state.location}</li>
<li><b>Email:</b> {this.state.email}</li>
</ul>
</div>
);
}
});
ReactDOM.render(
<UserGist source="https://api.github.com/users/potatogopher" />,
document.getElementById('gist')
);
为清晰起见,其他文件: 的 App.js
import React from 'react';
import HelloWorld from './HelloWorld';
import UserInfo from './UserInfo';
import UserGist from './UserGist';
export default function App(props) {
return (
<div>
<HelloWorld />
<UserInfo />
<UserGist source="https://api.github.com/users/potatogopher" />,
</div>
);
}
main.js
import React from 'react';
import { render } from 'react-dom';
import cubbie from 'cubbie'
import App from './components/App';
window.store = cubbie.createStore();
store.on(store.stateEvents, () => {
render(<App />, document.getElementById('root'));
console.log("app rendered")
});
任何帮助都会很棒!
答案 0 :(得分:0)
在做了一些研究之后,我发现我想要使用生命周期方法。另外@Hamms提到我上面的内容是无状态的。如果我想使用生命周期方法,我必须使用类。
我找到了一种格式化的方式,就像我希望的那样,但看起来很漂亮&#34; hacky&#34;。
mBinder = getBDBinder();
try {
ServiceManager.addService("test", mBinder);
BDLog.r(TAG, "create and add");
} catch (SecurityException e) {
BDLog.e(TAG, "Add service SecurityException");
}