I need to declare a javascript function as described below:
render: function() {
return (
<div>
<SomeReactClass somefunction="myFunction">
<script>
function myFunction(index, row) {
return index; <<<< error in this line
}
</script>
</div>
);
}
But, it does not compile: "Parse Error: Line 113: Unexpected token return"
How can I add tag using ReactJS?
I'm trying to use bootstrap-table detail view . The function is passed as parameter to the grid and it is used to render the row's detail. Also, see the example's source code for a better understanding.
When I try the way you're saying, it compiles, but does not work at all:
This is how it looks like (in example above):
This is what I'm getting with <SomeReactClass somefunction={myFunction}>
I know this is old, but i stumbled upon this recently and here is the best solution i found (i'm using it for browser polyfills, but it works for any code):
render: function() {
return (
<div>
<SomeReactClass somefunction="myFunction">
<script
dangerouslySetInnerHTML={{ __html:
`function myFunction(index, row) {return index;}`
}}
/>
</div>
);
}
Inside JSX, {...}
denotes a JavaScript expression. return index;
on its own is not a valid expression.
You have to explicitly create a string so that the {...}
are not interpreted by JSX. Template literals may be the easiest solution:
<script>{`
function myFunction(index, row) {
return index;
}
`}</script>
However, I have a hard time coming up with a reason why one would want to create a <script>
dynamically.
What you should probably do is pass the function directly to the component:
function myFunction(index, row) {
return index;
}
var Component = React.createElement({
render: function() {
return (
<div>
<SomeReactClass somefunction={myFunction} />
</div>
);
}
});
But it's hard to tell without you explaining what you are really trying to achieve here.
i think youre just looking for interpolation of your JS
function myFunction(index, row) {
return index;
}
render: function() {
return (
<div>
<SomeReactClass somefunction={myFunction}>
</div>
);
}
to interpolate javascript in jsx utilize curly braces {}
https://facebook.github.io/react/docs/jsx-in-depth.html#javascript-expressions
per your edit:
again, you need to be using the braces to interpolate your function. so inside of SomeReactClass
you need to be doing something like this in the render function:
<div>{this.props.myFunction(index, row)}</div>
most notably, you need to not only interpolate the function, by you also need to be executing it.
You should try this:
function myFunction(index, row) {
return index;
}
render: function() {
return (
<div>
<script
dangerouslySetInnerHTML={{
__html:myFunction()
}}
/>
</div>
);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.