问题
I'm using AutobahnJS I don't know how to use the same connection in another component.
I decided to make it manually by passing the session
argument to another component like this but that's doesn't work I don't know why
Main component:
class App extends Component {
componentWillMount(){
this.Call();
}
Call = () => {
var connection = new autobahn.Connection({ url: 'ws://127.0.0.1:9000/', realm: 'realm1' });
connection.onopen = function Pass (session) {
console.log(session, 'This I want to use it in anothr component')
};
connection.open();
}
render() {
return (
<div>
<Two Pass={this.Pass} />
</div>
)
}
}
export default App;
Child Component
class Two extends Component {
this.props.Pass(session); // if I console.log session will get error
//How to console log session here
render() {
return (
<div>
Child component
</div>
)
}
}
export default Two;
What is the best way to use the same connection(session) of Autobahn in another component?
update
class App extends Component {
constructor(props) {
super(props);
this.state = {
pageNumber: 1
}
this.sessionVar = this.sessionVar.bind(this)
}
回答1:
Maybe you can try something like this:
let sessionVar = undefined
class App extends Component {
componentWillMount(){
this.Call();
}
Call = () => {
var connection = new autobahn.Connection({ url: 'ws://127.0.0.1:9000/', realm: 'realm1' });
connection.onopen = function Pass (session) {
console.log(session, 'This I want to use it in anothr component')
sessionVar = session
};
connection.open();
}
render() {
return (
<div>
<Two Pass={this.Pass} session={sessionVar} />
</div>
)
}
}
you can also use state and it will probably be easier that would look like this:
Call = () => {
var connection = new autobahn.Connection({ url: 'ws://127.0.0.1:9000/', realm: 'realm1' });
connection.onopen = function Pass (session) {
console.log(session, 'This I want to use it in anothr component')
this.setState({session})
};
connection.open();
}
render() {
return (
<div>
<Two session={this.state.session} />
</div>
)
}
}
Then you can do this in your child component:
class Two extends Component {
componentDidMount(){
console.log(this.props.session)
}
render() {
return (
<div>
Child component
</div>
)
}
}
export default Two;
来源:https://stackoverflow.com/questions/49260017/pass-function-argument-to-another-component-reactjs